fig-tree-evaluator 3.0.0-preview.4 → 3.0.0-preview.6
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 +10 -0
- package/build/authoring/index.js +1 -0
- package/build/chunks/engine.js +1 -0
- package/build/chunks/shared.js +1 -1
- package/build/index.d.ts +22 -16
- package/build/index.js +1 -1
- package/package.json +8 -1
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
interface FallbackCoverage {
|
|
2
|
+
uncovered: (string | number)[][];
|
|
3
|
+
}
|
|
4
|
+
interface FallbackCoverageOptions {
|
|
5
|
+
timeout?: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
declare const fallbackCoverage: (fig: unknown, expression: unknown, options?: FallbackCoverageOptions) => FallbackCoverage;
|
|
9
|
+
|
|
10
|
+
export { fallbackCoverage };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as e,v as t,t as r}from"../chunks/engine.js";import"../chunks/shared.js";const s=(s,o,i)=>{if(!(s instanceof e))throw new TypeError("fallbackCoverage() takes a FigTree instance");const{artifact:c,options:h}=t(s.compile(o),i),l=new n(h.strictDataPaths??!1);if(void 0!==h.timeout){const e="skeleton"===c.root.kind?a(null,c.root.vars):null;return{uncovered:c.holes.filter(t=>void 0===t.timeoutFallback||l.mayThrow(t.node,e)).map(e=>r(e.node.path))}}const u=[],d=(e,t)=>{if("skeleton"===e.kind){const r=a(t,e.vars);for(const t of e.holes)d(t.node,r)}else l.mayThrow(e,t)&&u.push(r(e.path))};return d(c.root,null),{uncovered:u}},a=(e,t)=>void 0===t?e:{vars:t,parent:e};class n{strict;vars=new Map;bodies=new Map;constructor(e){this.strict=e}mayThrow(e,t){switch(e.kind){case"constant":return!1;case"invalid":case"elements":case"entries":return!0;case"reference":return this.referenceMayThrow(e,t);case"skeleton":{const r=a(t,e.vars);return e.holes.some(e=>this.mayThrow(e.node,r))}case"operator":{if(void 0!==e.fallback)return this.mayThrow(e.fallback,a(t,e.vars));const r=e.entry.instanceDefaults;return void 0===r||!Object.hasOwn(r,"fallback")}case"fragmentCall":return void 0!==e.fallback?this.mayThrow(e.fallback,a(t,e.vars)):void 0===e.entry||("dynamic"===e.argumentsMode||this.bodyMayThrow(e.entry))}return e}referenceMayThrow(e,t){switch(e.namespace){case"data":case"element":return this.strict&&e.segments.length>0;case"index":return!1;case"params":return!0;case"vars":return this.strict&&e.segments.length>1||this.varMayThrow(e.segments[0],t)}return e.namespace}varMayThrow(e,t){for(let r=t;null!==r;r=r.parent){if("string"!=typeof e||!Object.hasOwn(r.vars,e))continue;const t=r.vars[e],s=this.vars.get(t);if(void 0!==s)return s;this.vars.set(t,!0);const a=this.mayThrow(t,r);return this.vars.set(t,a),a}return!0}bodyMayThrow(e){const t=this.bodies.get(e);if(void 0!==t)return t;const r=this.mayThrow(e.body,null);return this.bodies.set(e,r),r}}export{s as fallbackCoverage};
|
|
@@ -0,0 +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};
|
package/build/chunks/shared.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={unknownOperator:"unknown-operator",typeCheck:"type-check",operatorFailure:"operator-failure",timeout:"timeout",requestTimeout:"request-timeout",aborted:"aborted",unknownNodeKey:"unknown-node-key",unresolvedVar:"unresolved-var",unrecognizedIdentifier:"unrecognized-identifier",depthCeiling:"depth-ceiling",nonFiniteResult:"non-finite-result",escapedHandle:"escaped-handle",emptyAggregate:"empty-aggregate",malformedNode:"malformed-node",unknownFragment:"unknown-fragment",positionalArity:"positional-arity",invalidVars:"invalid-vars",invalidReference:"invalid-reference",uselessModifier:"useless-modifier",unreferencedVar:"unreferenced-var",missingRequired:"missing-required",unresolvedParam:"unresolved-param",unresolvedBinding:"unresolved-binding",deadBinding:"dead-binding",invalidAs:"invalid-as",maxDepthExceeded:"max-depth",maxNodesExceeded:"max-nodes",returnsMismatch:"returns-mismatch",operatorValidate:"operator-validate",missingDataPath:"missing-data-path",shadowedVar:"shadowed-var",varCycle:"var-cycle",bareVars:"bare-vars",fragmentCycle:"fragment-cycle",unboundToken:"unbound-token",unusedSubstitution:"unused-substitution",
|
|
1
|
+
class e extends Error{code;path;operator;fragment;fragmentPath;errorData;related;cause;issues;trace;constructor(e){super(e.message),this.name="FigTreeError",this.code=e.code,this.path=e.path,void 0!==e.operator&&(this.operator=e.operator),void 0!==e.fragment&&(this.fragment=e.fragment),void 0!==e.fragmentPath&&(this.fragmentPath=e.fragmentPath),void 0!==e.errorData&&(this.errorData=e.errorData),void 0!==e.related&&(this.related=e.related),void 0!==e.cause&&(this.cause=e.cause),void 0!==e.issues&&(this.issues=e.issues),void 0!==e.trace&&(this.trace=e.trace)}prettyPrint(){const e=this.operator?` (operator: ${this.operator})`:"",n=this.path.length>0?` at ${t(this.path)}`:"",r=`${this.code}${e}${n}`,a=this.errorData&&Object.keys(this.errorData).length>0?`\n${JSON.stringify(this.errorData,null,2)}`:"";return`${r}\n${this.message}${a}`}}const n=n=>n instanceof e,t=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:0===n?e:`.${e}`).join(""),r={unknownOperator:"unknown-operator",typeCheck:"type-check",operatorFailure:"operator-failure",timeout:"timeout",requestTimeout:"request-timeout",aborted:"aborted",unknownNodeKey:"unknown-node-key",unresolvedVar:"unresolved-var",unrecognizedIdentifier:"unrecognized-identifier",depthCeiling:"depth-ceiling",nonFiniteResult:"non-finite-result",escapedHandle:"escaped-handle",emptyAggregate:"empty-aggregate",malformedNode:"malformed-node",unknownFragment:"unknown-fragment",positionalArity:"positional-arity",invalidVars:"invalid-vars",invalidReference:"invalid-reference",uselessModifier:"useless-modifier",unreferencedVar:"unreferenced-var",missingRequired:"missing-required",unresolvedParam:"unresolved-param",unresolvedBinding:"unresolved-binding",deadBinding:"dead-binding",invalidAs:"invalid-as",maxDepthExceeded:"max-depth",maxNodesExceeded:"max-nodes",returnsMismatch:"returns-mismatch",fallbackMismatch:"fallback-mismatch",operatorValidate:"operator-validate",missingDataPath:"missing-data-path",shadowedVar:"shadowed-var",varCycle:"var-cycle",bareVars:"bare-vars",fragmentCycle:"fragment-cycle",unboundToken:"unbound-token",unusedSubstitution:"unused-substitution",inertReferenceToken:"inert-reference-token",invalidDefinition:"invalid-definition",invalidName:"invalid-name",reservedName:"reserved-name",invalidNullPolicy:"invalid-null-policy",duplicateOperator:"duplicate-operator",invalidOptions:"invalid-options"},a=()=>{},i=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then,s=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),o=e=>{if("object"!=typeof e||null===e||Array.isArray(e))return!1;const n=Object.getPrototypeOf(e);return n===Object.prototype||null===n},l=(e,n)=>{if(e===n)return 0;const t=e.length+1,r=n.length+1;let a=Array.from({length:r},(e,n)=>n);for(let i=1;i<t;i++){const t=[i];for(let s=1;s<r;s++){const r=a[s-1]+(e[i-1]===n[s-1]?0:1);t.push(Math.min(a[s]+1,t[s-1]+1,r))}a=t}return a[r-1]},d=(e,n)=>{let t,r=3;for(const a of n){const n=l(e,a);n<r&&(t=a,r=n)}return t},u=e=>{let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")},c=e=>{let n;return()=>(void 0===n&&(n=(async()=>e())()),n)},m=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"literal"in e,f=(e,n)=>{const t=p(e),r=p(n);return!(!t.any&&!r.any)||(void 0!==t.literals&&void 0!==r.literals?t.literals.some(e=>r.literals.includes(e)):void 0!==t.literals?t.literals.some(e=>h(e,r.basics)):void 0!==r.literals?r.literals.some(e=>h(e,t.basics)):t.basics.some(e=>r.basics.includes(e)||"integer"===e&&r.basics.includes("number")||"number"===e&&r.basics.includes("integer")))},p=e=>{if(m(e))return{any:!1,basics:[],literals:e.literal};const n="string"==typeof e?[e]:e;return{any:n.includes("any"),basics:n}},h=(e,n)=>"string"==typeof e?n.includes("string"):"boolean"==typeof e?n.includes("boolean"):n.includes("number")||Number.isInteger(e)&&n.includes("integer"),g=/*#__PURE__*/new Set(["operator","fragment","parameters","fallback","noCache","vars","//"]),v=/*#__PURE__*/new Set([...g,"data","params","element","index","d","v","p","e","i","literal"]),y=e=>"string"!=typeof e?{ok:!1,reason:"a name must be a string"}:""===e?{ok:!1,reason:"a name must be non-empty"}:e.startsWith("$")?{ok:!1,reason:"a name may not start with '$'"}:/[.[\]]/.test(e)?{ok:!1,reason:"a name may not contain '.', '[' or ']'"}:{ok:!0},b=Symbol("figtree.path.wildcard"),k=e=>"string"==typeof e||"number"==typeof e||e===b,$={found:!1,value:void 0},x=e=>{const n=[];let t="",r=!1,a=0;const i=()=>{r&&(n.push(t),t="",r=!1)};for(;a<e.length;){const s=e[a];if("."!==s){if("["===s){i();const{segment:t,next:r}=w(e,a);n.push(t),a=r;continue}t+=s,r=!0,a++}else i(),a++}return i(),n},w=(e,n)=>{let t=n+1;if(t>=e.length)throw A(e,'unterminated "["');const r=e[t];if("*"===r){if("]"!==e[t+1])throw A(e,'expected "]" after "[*"');return{segment:b,next:t+2}}if('"'===r||"'"===r){const n=r;t++;let a="";for(;t<e.length;){const r=e[t];if("\\"===r){const n=e[t+1];if(void 0===n)throw A(e,"trailing escape in quoted key");a+=n,t+=2;continue}if(r===n){if("]"!==e[t+1])throw A(e,'expected "]" after quoted key');return{segment:a,next:t+2}}a+=r,t++}throw A(e,"unterminated quoted key")}let a="";for(;t<e.length&&e[t]>="0"&&e[t]<="9";)a+=e[t],t++;if(a.length>0&&"]"===e[t])return{segment:Number(a),next:t+1};throw A(e,'expected a number, "*", or a quoted key inside "[…]"')},A=(e,n)=>new Error(`Invalid path "${e}": ${n}`),j=(e,n)=>P(e,(e=>Array.isArray(e)?e.slice():x(e))(n),0),P=(e,n,t)=>{if(t>=n.length)return{found:!0,value:e};const r=n[t];if(r===b){if(!Array.isArray(e))return $;const r=t+1;if(r>=n.length)return{found:!0,value:e};return{found:!0,value:e.map(e=>{const t=P(e,n,r);return t.found?t.value:null})}}const a=D(e,r);return a.found?P(a.value,n,t+1):$},D=(e,n)=>{if(null===e||"object"!=typeof e)return $;if(Array.isArray(e)){const t="number"==typeof n?n:N(n);return void 0===t||t<0||t>=e.length?$:{found:!0,value:e[t]}}const t=String(n);return Object.prototype.propertyIsEnumerable.call(e,t)?{found:!0,value:e[t]}:$},N=e=>/^\d+$/.test(e)?Number(e):void 0,S=e=>e.map(e=>"string"==typeof e?N(e)??e:e),q={data:"data",d:"data",vars:"vars",v:"vars",params:"params",p:"params",element:"element",e:"element",index:"index",i:"index"},O=e=>{if(!e.startsWith("$"))return null;const n=/^\$([^.[]*)/.exec(e)[1];return{token:n,rest:e.slice(1+n.length)}},W=e=>""===e?[]:x(e.startsWith(".")?e.slice(1):e),C=e=>`${e}Index`,E=(e,n)=>{for(const t of n){if(e===t)return"element";if(e===C(t))return"index"}return null},V=(e,n)=>{const t=O(e);if(null===t)return{kind:"plain"};const{token:a,rest:i}=t,s=q[a];if(void 0===s){const e=void 0===n?.bindings?null:E(a,n.bindings);return null===e?{kind:"unrecognized"}:z(a,i,e)}if(""===i)return"vars"===s?{kind:"invalid",namespace:s,code:r.bareVars,reason:"'$vars' must name a var — there is no whole-scope value"}:{kind:"reference",namespace:s,segments:[],drill:i};if("index"===s)return{kind:"invalid",namespace:s,reason:"'$index' is bare-only — it cannot be drilled"};try{return{kind:"reference",namespace:s,segments:W(i),drill:i}}catch(e){return{kind:"invalid",namespace:s,reason:e.message}}},z=(e,n,t)=>{if("index"===t)return""!==n?{kind:"invalid",namespace:t,reason:"the index binding is bare-only — it cannot be drilled"}:{kind:"reference",namespace:t,segments:[],drill:n,binding:e};try{return{kind:"reference",namespace:t,segments:W(n),drill:n,binding:e}}catch(e){return{kind:"invalid",namespace:t,reason:e.message}}},M=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:e===b?"[*]":I(e,0===n)).join(""),F=/[.[\]"\\]/,I=(e,n)=>""===e||F.test(e)?`["${e.replace(/[\\"]/g,e=>`\\${e}`)}"]`:n?e:`.${e}`,R=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/,T=e=>R.test(e),B=(e,n)=>{const t=M(n);return""===t?`$${e}`:t.startsWith("[")?`$${e}${t}`:`$${e}.${t}`},Z=e=>B("data",e),_=/*#__PURE__*/new Set(["fallback","noCache","vars","//"]),G=500,H={kind:"operator"},J={kind:"fragment"},K={kind:"plain"},L=e=>({kind:"malformed",message:e}),Q=(e,n)=>{const t="operator"in e,r="fragment"in e,a=[];for(const t in e)t.startsWith("$")&&n(t.slice(1))&&a.push(t);return t&&r?L("'operator' and 'fragment' may not share a node"):(t||r)&&a.length>0?L(`a canonical '${t?"operator":"fragment"}' key may not sit beside the shorthand key '${a[0]}'`):t?H:r?J:a.length>=2?L(`one node, one invocation: found ${a.map(e=>`'${e}'`).join(" and ")}`):1===a.length?{kind:"shorthand",key:a[0]}:K},U=(e,n)=>{if(!o(e))return!1;if("operator"in e||"fragment"in e)return!0;for(const t in e)if(t.startsWith("$")&&n(t.slice(1)))return!0;return!1},X=(e,n)=>{const t=e.positionalParams;if(void 0===t)return null;const r=e.restParam,a=null===r?t.length:t.length-1;return n>a&&null===r?null:{bound:Math.min(n,a),restAt:null!==r&&n>=a?a:null}},Y=e=>{const n=e.positionalParams?.[0];return void 0===n?null:n.startsWith("...")?e.restParam:n},ee=["path","default"];export{Z as A,u as B,G as D,r as E,e as F,ee as G,g as R,_ as S,b as W,U as a,O as b,Q as c,M as d,x as e,s as f,y as g,v as h,o as i,j,B as k,n as l,m,T as n,S as o,X as p,d as q,V as r,Y as s,f as t,E as u,k as v,C as w,a as x,c as y,i as z};
|
package/build/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
declare const version = "3.0.0-preview.
|
|
1
|
+
declare const version = "3.0.0-preview.6";
|
|
2
2
|
|
|
3
3
|
interface HttpRequest {
|
|
4
4
|
url: string;
|
|
@@ -55,6 +55,7 @@ declare const ErrorCodes: {
|
|
|
55
55
|
readonly maxDepthExceeded: "max-depth";
|
|
56
56
|
readonly maxNodesExceeded: "max-nodes";
|
|
57
57
|
readonly returnsMismatch: "returns-mismatch";
|
|
58
|
+
readonly fallbackMismatch: "fallback-mismatch";
|
|
58
59
|
readonly operatorValidate: "operator-validate";
|
|
59
60
|
readonly missingDataPath: "missing-data-path";
|
|
60
61
|
readonly shadowedVar: "shadowed-var";
|
|
@@ -63,7 +64,6 @@ declare const ErrorCodes: {
|
|
|
63
64
|
readonly fragmentCycle: "fragment-cycle";
|
|
64
65
|
readonly unboundToken: "unbound-token";
|
|
65
66
|
readonly unusedSubstitution: "unused-substitution";
|
|
66
|
-
readonly tokenRenumber: "token-renumber";
|
|
67
67
|
readonly inertReferenceToken: "inert-reference-token";
|
|
68
68
|
readonly invalidDefinition: "invalid-definition";
|
|
69
69
|
readonly invalidName: "invalid-name";
|
|
@@ -73,7 +73,7 @@ declare const ErrorCodes: {
|
|
|
73
73
|
readonly invalidOptions: "invalid-options";
|
|
74
74
|
};
|
|
75
75
|
|
|
76
|
-
type Severity = 'error' | 'warning'
|
|
76
|
+
type Severity = 'error' | 'warning';
|
|
77
77
|
interface Issue {
|
|
78
78
|
severity: Severity;
|
|
79
79
|
code: FigTreeErrorCode;
|
|
@@ -87,7 +87,6 @@ interface Issue {
|
|
|
87
87
|
interface ValidationResult {
|
|
88
88
|
valid: boolean;
|
|
89
89
|
issues: Issue[];
|
|
90
|
-
timeoutShielded: boolean;
|
|
91
90
|
}
|
|
92
91
|
|
|
93
92
|
declare const LAZY_HANDLE: unique symbol;
|
|
@@ -176,7 +175,6 @@ interface FigTreeErrorInit {
|
|
|
176
175
|
code: FigTreeErrorCode;
|
|
177
176
|
message: string;
|
|
178
177
|
path: (string | number)[];
|
|
179
|
-
holePath?: (string | number)[];
|
|
180
178
|
operator?: string;
|
|
181
179
|
fragment?: string;
|
|
182
180
|
fragmentPath?: (string | number)[];
|
|
@@ -189,7 +187,6 @@ interface FigTreeErrorInit {
|
|
|
189
187
|
declare class FigTreeError extends Error {
|
|
190
188
|
code: FigTreeErrorCode;
|
|
191
189
|
path: (string | number)[];
|
|
192
|
-
holePath?: (string | number)[];
|
|
193
190
|
operator?: string;
|
|
194
191
|
fragment?: string;
|
|
195
192
|
fragmentPath?: (string | number)[];
|
|
@@ -470,7 +467,7 @@ interface FragmentParameter {
|
|
|
470
467
|
}
|
|
471
468
|
|
|
472
469
|
type EvaluationOptions = Omit<FigTreeOptions, 'operators' | 'fragments'>;
|
|
473
|
-
type CallOptions = Pick<FigTreeOptions, 'data' | 'signal' | 'timeout' | '
|
|
470
|
+
type CallOptions = Pick<FigTreeOptions, 'data' | 'signal' | 'timeout' | 'trace'>;
|
|
474
471
|
type OnlyCallOptions<CallOpts> = CallOpts & {
|
|
475
472
|
[Key in Exclude<keyof CallOpts, keyof CallOptions>]: never;
|
|
476
473
|
};
|
|
@@ -503,20 +500,22 @@ interface FigTreeOptions {
|
|
|
503
500
|
maxSize?: number;
|
|
504
501
|
maxTime?: number;
|
|
505
502
|
};
|
|
506
|
-
runtimeTypeCheck?: boolean;
|
|
507
|
-
mode?: 'throw' | 'report';
|
|
508
503
|
trace?: boolean;
|
|
509
504
|
}
|
|
505
|
+
type OptionsUpdate = {
|
|
506
|
+
[Key in keyof FigTreeOptions]?: (Key extends MergedBlock ? Removable<NonNullable<FigTreeOptions[Key]>> : FigTreeOptions[Key]) | null;
|
|
507
|
+
};
|
|
508
|
+
type MergedBlock = 'fragments' | 'operatorDefaults' | 'http' | 'graphQL' | 'cache';
|
|
509
|
+
type Removable<Block> = {
|
|
510
|
+
[Key in keyof Block]?: Block[Key] | null;
|
|
511
|
+
};
|
|
510
512
|
interface EvaluationResult {
|
|
511
513
|
result: unknown;
|
|
512
|
-
|
|
513
|
-
trace?: TraceNode;
|
|
514
|
+
trace: TraceNode;
|
|
514
515
|
}
|
|
515
516
|
type NoOptions = Record<never, never>;
|
|
516
517
|
type Merge<Instance, Call> = Omit<Instance, keyof Call> & Call;
|
|
517
518
|
type ResultShape<O> = O extends {
|
|
518
|
-
mode: 'report';
|
|
519
|
-
} | {
|
|
520
519
|
trace: true;
|
|
521
520
|
} ? EvaluationResult : unknown;
|
|
522
521
|
|
|
@@ -551,9 +550,9 @@ interface FragmentInfo {
|
|
|
551
550
|
declare class FigTree<InstanceOpts extends FigTreeOptions = NoOptions> {
|
|
552
551
|
private state;
|
|
553
552
|
private readonly results;
|
|
554
|
-
readonly version = "3.0.0-preview.
|
|
553
|
+
readonly version = "3.0.0-preview.6";
|
|
555
554
|
constructor(options?: InstanceOpts);
|
|
556
|
-
updateOptions(options?:
|
|
555
|
+
updateOptions(options?: OptionsUpdate): void;
|
|
557
556
|
clearCache(): void;
|
|
558
557
|
getOptions(): EvaluationOptions;
|
|
559
558
|
getOperators(): OperatorInfo[];
|
|
@@ -823,5 +822,12 @@ interface ShorthandOptions extends NameOptions {
|
|
|
823
822
|
getAsReference?: boolean;
|
|
824
823
|
}
|
|
825
824
|
|
|
825
|
+
interface FallbackCoverage {
|
|
826
|
+
uncovered: (string | number)[][];
|
|
827
|
+
}
|
|
828
|
+
interface FallbackCoverageOptions {
|
|
829
|
+
timeout?: number;
|
|
830
|
+
}
|
|
831
|
+
|
|
826
832
|
export { ARRAY, AxiosClient, CompiledExpression, ErrorCodes, EvaluationData, FetchClient, FigTree, FigTreeError, OBJECT, OPERATOR_CATEGORIES, OperatorFailure, PostgresConnection, SQLiteConnection, WILDCARD, compareValues, coreOperators, deepEqual, defineOperator, httpOperators, inspect, isFigTreeError, isOperatorFailure, isTruthy, parsePath, renderText, resolvePath, sqlOperators, version };
|
|
827
|
-
export type { AxiosErrorLike, AxiosLike, BasicType, CacheStore, CacheTraceEvent, CallOptions, CanonicalOptions, CategoryHintMap, CategoryHints, CompiledNullPolicy, ConditionalNullPolicy, Constraints, Dependencies, EvaluationMode, EvaluationOptions, EvaluationResult, ExpectedType, FetchLike, FetchResponseLike, FigTreeErrorCode, FigTreeErrorInit, FigTreeOptions, FragmentDefinition, FragmentHints, FragmentInfo, FragmentMigrationResult, FragmentParameter, FragmentParameterDeclaration, HttpClient, HttpRequest, InspectDependencies, InspectIssue, InspectNode, InspectReport, Issue, KeyOverwriteTraceEvent, KnownTraceEvent, LazyValue, LiteralType, Merge, MigrationIssue, MigrationResult, NameOptions, NoOptions, NullPolicy, NullPolicyValue, ObjectClass, OnlyCallOptions, OperatorCategory, OperatorContext, OperatorDefinition, OperatorEvaluate, OperatorFailureInit, OperatorHintMap, OperatorHints, OperatorInfo, OperatorValidate, ParamValue, ParameterDeclaration, ParameterDeclarations, ParameterInfo, PathSegment, PerElement, PgClientLike, PositionalLayout, PositionalShape, QueryTraceEvent, ReferenceNamespace, ReferenceRecognition, ReferenceScope, Registry, RenderTraceEvent, RequestTraceEvent, ResolveResult, ResolvedParams, ResultShape, Settlement, SettlementStream, Severity, ShieldedFallbackTraceEvent, ShorthandOptions, Spelling, SqlConnection, SqlRequest, SqliteDatabaseLike, TraceEvent, TraceKind, TraceNode, TraceStatus, TypeCheckResult, TypeDeclaration, TypeOf, TypeSeeds, V2Options, ValidateFinding, ValidateHelpers, ValidatedOperatorDefinition, ValidatedParameter, ValidationResult, Wildcard };
|
|
833
|
+
export type { AxiosErrorLike, AxiosLike, BasicType, CacheStore, CacheTraceEvent, CallOptions, CanonicalOptions, CategoryHintMap, CategoryHints, CompiledNullPolicy, ConditionalNullPolicy, Constraints, Dependencies, EvaluationMode, EvaluationOptions, EvaluationResult, ExpectedType, FallbackCoverage, FallbackCoverageOptions, FetchLike, FetchResponseLike, FigTreeErrorCode, FigTreeErrorInit, FigTreeOptions, FragmentDefinition, FragmentHints, FragmentInfo, FragmentMigrationResult, FragmentParameter, FragmentParameterDeclaration, HttpClient, HttpRequest, InspectDependencies, InspectIssue, InspectNode, InspectReport, Issue, KeyOverwriteTraceEvent, KnownTraceEvent, LazyValue, LiteralType, Merge, MigrationIssue, MigrationResult, NameOptions, NoOptions, NullPolicy, NullPolicyValue, ObjectClass, OnlyCallOptions, OperatorCategory, OperatorContext, OperatorDefinition, OperatorEvaluate, OperatorFailureInit, OperatorHintMap, OperatorHints, OperatorInfo, OperatorValidate, OptionsUpdate, ParamValue, ParameterDeclaration, ParameterDeclarations, ParameterInfo, PathSegment, PerElement, PgClientLike, PositionalLayout, PositionalShape, QueryTraceEvent, ReferenceNamespace, ReferenceRecognition, ReferenceScope, Registry, RenderTraceEvent, RequestTraceEvent, ResolveResult, ResolvedParams, ResultShape, Settlement, SettlementStream, Severity, ShieldedFallbackTraceEvent, ShorthandOptions, Spelling, SqlConnection, SqlRequest, SqliteDatabaseLike, TraceEvent, TraceKind, TraceNode, TraceStatus, TypeCheckResult, TypeDeclaration, TypeOf, TypeSeeds, V2Options, ValidateFinding, ValidateHelpers, ValidatedOperatorDefinition, ValidatedParameter, ValidationResult, Wildcard };
|
package/build/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e,g as t,h as r,r as a,i as n,D as o,E as i,b as s,c as l,j as c,k as u,d,S as p,n as m,a as f,p as h,s as v,l as y,e as g,m as b,o as w,q as k,t as $,u as x,R as j,F as P,v as O,w as A,x as D,y as N,W as C,z as S,A as q,G as T,B as E}from"./chunks/shared.js";const z=[!1,null,0,""],M=e=>-1===z.indexOf(e),F=(e,t)=>"number"==typeof e&&"number"==typeof t?e<t?-1:e>t?1:0:L(String(e),String(t)),L=(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},R="<array>",V="<object>",I=e=>null===e?"":"string"==typeof e?e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?R:V,Q=e=>e.trim(),J=/\s+$/,U=/^\s+/,G=e=>e.replace(J,""),W=e=>e.replace(U,""),B=e=>Array.from(e),K=(e,t)=>{const[r,a]=String(e).split("e"),n=void 0!==a?Number(a)+t:t;return Number(`${r}e${n}`)},H=Object.prototype.hasOwnProperty,_=(e,t)=>{for(const r of e.keys())if(X(r,t))return r},X=(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--&&X(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=_(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=_(t,n),!n))return!1;if(!X(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(H.call(e,r)&&++a&&!H.call(t,r))return!1;if(!(r in t)||!X(e[r],t[r]))return!1}return Object.keys(t).length===a}}return e!=e&&t!=t},Y="3.0.0-preview.4",Z={ok:!0},ee=e=>null===e?"null":Array.isArray(e)?"array":typeof e,te=(e,t)=>({ok:!1,expected:e,actual:ee(t)}),re=(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}},ae=e=>"null"===e||"any"===e||!!Array.isArray(e)&&(e.includes("null")||e.includes("any")),ne=/*#__PURE__*/new Set(["any","string","number","boolean","array","object","null","integer"]),oe=t=>{if("string"==typeof t)return ne.has(t);if(Array.isArray(t))return t.length>0&&t.every(e=>"string"==typeof e&&ne.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},ie=(e,r)=>{if(t(r)){if(-1!==r.literal.indexOf(e))return Z;const t=r.literal.map(e=>JSON.stringify(e)).join(", ");return te(`one of ${t}`,e)}return"string"==typeof r?re(e,r)?Z:te(r,e):r.some(t=>re(e,t))?Z:te(r.join(" | "),e)},se=(e,t)=>{if(void 0!==t.length){if(!Array.isArray(e))return te("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 te("array",e);const r=t.homogeneous;if(e.length>0){if(void 0===r.find(t=>e.every(e=>re(e,t))))return{ok:!1,expected:`homogeneous array of ${r.join(" | ")}`,actual:le(e)}}}if(t.elementShape){if(!Array.isArray(e))return te("array",e);for(let r=0;r<e.length;r++){const a=de(e[r],t.elementShape);if(!a.ok)return a}}return Z},le=e=>{const t=ee(e[0]),r=e.find(e=>ee(e)!==t);return void 0===r?`array of ${t}`:`${ee(r)} beside ${t}`},ce=["length","homogeneous","elementShape"],ue=t=>{if(!e(t))return te("a constraints object",t);for(const e of Object.keys(t))if(!ce.includes(e))return{ok:!1,expected:`one of ${ce.join(", ")}`,actual:e};const{length:r,homogeneous:a,elementShape:n}=t;if(void 0!==r&&(!Number.isInteger(r)||r<0))return te("a non-negative integer length",r);if(!(void 0===a||Array.isArray(a)&&oe(a)))return te("a non-empty array of basic types",a);if(void 0!==n){if(!e(n))return te("an object of declarations",n);for(const[t,r]of Object.entries(n)){if(!e(r))return te(`a declaration for "${t}"`,r);if(void 0!==r.type&&!oe(r.type))return te(`a vocabulary type for "${t}"`,r.type);if(void 0!==r.required&&"boolean"!=typeof r.required)return te(`a boolean "required" for "${t}"`,r.required);if(void 0!==r.constraints){const e=ue(r.constraints);if(!e.ok)return e}}}return Z},de=(t,r)=>{if(!e(t))return te("object",t);const a=Object.keys(r);for(let e=0;e<a.length;e++){const n=a[e],o=r[n],i=Object.prototype.hasOwnProperty.call(t,n),s=!1!==o.required;if(i){if(void 0!==o.type){const e=ie(t[n],o.type);if(!e.ok)return e}if(void 0!==o.constraints){const e=se(t[n],o.constraints);if(!e.ok)return e}}else if(s)return{ok:!1,expected:`property "${n}"`,actual:"missing"}}return Z},pe=(e,t,r)=>{if(!r||!Array.isArray(e))return se(e,t);const{length:a,...n}=t;if(void 0!==a){const t=se(e,{length:a});if(!t.ok)return t}return se(e.filter(e=>null!==e),n)},me=["logic","comparison","math","string","array","data","io","other"],fe=Symbol("fig-tree:EvaluationData"),he=Symbol("fig-tree:validated-operator"),ve=e=>"object"==typeof e&&null!==e&&!0===e[he],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 i=n+1;for(;i<e.length&&e[i]>="0"&&e[i]<="9";)i++;if(i>n+1){const r=e.slice(n,i);a(),t.push({kind:"positional",raw:r,index:Number(r.slice(1))}),n=i;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,t)=>{const r={registry:t,maxDepth:0};return{constant:we(r,e,0),depth:r.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 r in t){if("operator"===r||"fragment"===r||"vars"===r||"//"===r)return!1;if(r.startsWith("$")&&ke(e.registry,r.slice(1)))return!1}for(const a in t)if(!we(e,t[a],r+1))return!1;return!0}return!0},ke=(e,t)=>"literal"===t||void 0!==jr(e,t)||e.fragments.has(t),$e=(e,t)=>({parent:e,key:t}),xe=e=>{const t=[];for(let r=e;null!==r;r=r.parent)t.push(r.key);return t.reverse()},je=e=>{e.sort((e,t)=>e.order-t.order)},Pe=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},Ae=(e,t,r)=>void 0===r?null===e:("element"===t?e:`${e??""}Index`)===r,De=(e,t,r)=>{const a=new Set;let n=e;return t.forEach((e,t)=>{n=Ne(n,e.at,r[t],a)}),n},Ne=(e,t,r,a)=>{const n=Ce(e,a),[o,...i]=t;return n[o]=0===i.length?r:Ne(n[o],i,r,a),n},Ce=(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"]),qe=(e,t,r={})=>{const a={registry:t,recognizes:e=>ke(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($e,null),o=Me(a,e,n,0);Ee(a);const i=$t(a,o);je(a.issues);const s=Pe(a.issues),l={nodeCount:a.nodeCount,maxDepth:a.maxDepth,dependencies:{dataPaths:a.dataPaths,dynamic:a.dynamic,operators:[...a.operators],fragments:[...a.fragmentNames]},identityOnly:a.identityOnly};return{root:o,holes:i,issues:a.issues,hasErrors:s,timeoutShielded:i.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:i,maxDepth:s,identityOnly:l}=e,c=e.dependencies.dynamic;for(const e of t){const t=r.get(e.name);if(void 0!==t){i+=t.nodeCount,s=Math.max(s,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:i,maxDepth:s,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:i.unresolvedBinding,message:`'${a}' names an iterator binding, but no enclosing iterator binds it here`})},ze=(e,t,r,a,n,o,i={})=>{const s={severity:t,code:r,message:a,path:xe(n)};void 0!==i.operator&&(s.operator=i.operator),void 0!==i.parameter&&(s.parameter=i.parameter),void 0!==i.suggestion&&(s.suggestion=i.suggestion);const l={issue:s,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 ze(e,"error",i.depthCeiling,`the expression nests deeper than the engine's ceiling of ${o} levels — descent stopped here`,r,n),e.nodeCount++,Re(t,r,n);const s=Fe(e,t,r,a,n);return"operator"!==s.kind&&"fragmentCall"!==s.kind&&"reference"!==s.kind&&"invalid"!==s.kind||e.nodeCount++,s},Fe=(e,t,r,a,o)=>null==t?Le(t??null,r,o):"number"==typeof t||"boolean"==typeof t?Le(t,r,o):"string"==typeof t?Ve(e,t,r,o):Array.isArray(t)?Ie(e,t,r,a,o):n(t)?Qe(e,t,r,a,o):(e.identityOnly=!0,Le(t,r,o)),Le=(e,t,r)=>({kind:"constant",value:e,path:t,order:r}),Re=(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 Le(t,r,n);case"unrecognized":{const a=ze(e,"warning",i.unrecognizedIdentifier,`'${t}' matches no reference namespace and will pass through as data`,r,n),o=s(t);return null!==o&&e.unrecognized.push({token:o.token,issue:a,raw:t}),Le(t,r,n)}case"invalid":return ze(e,"error",o.code??i.invalidReference,`'${t}': ${o.reason}`,r,n),Re(t,r,n);case"reference":{const{namespace:a,segments:i,drill:s,binding:l}=o;return void 0!==l?{kind:"reference",namespace:a,segments:i,raw:t,binding:l,path:r,order:n}:("data"===a&&(0===i.length?e.dynamic=!0:Ye(e,i,s.startsWith(".")?s.slice(1):void 0,r)),{kind:"reference",namespace:a,segments:i,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:Me(e,void 0===t?null:t,$e(r,n),a+1)})),i=t.some(e=>void 0===e);return kt(e,t,o,!0,i,void 0,r,n)},Qe=(e,t,r,a,n)=>{const o=l(t,e.recognizes);switch(o.kind){case"malformed":return ze(e,"error",i.malformedNode,o.message,r,n),Re(t,r,n);case"operator":return Je(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 bt(e,t,r,a,n)}},Je=(e,t,r,a,n)=>{const o=t.operator;if("string"!=typeof o)return ze(e,"error",i.malformedNode,"the 'operator' value must be a literal string",r,n),Re(t,r,n);if("literal"===o)return mt(e,t,t.value,"value"in t,r,n);const s=jr(e.registry,o);if(void 0===s){const a=m(o,Pt(e));return ze(e,"error",i.unknownOperator,`'${o}' names no registered operator${a?` — did you mean '${a}'?`:""}`,r,n,{suggestion:a}),Re(t,r,n)}const l=Ue(e,s,r,n),c=[];for(const o in t){const s=t[o];"operator"!==o&&"//"!==o&&void 0!==s&&(Ge(e,l,o,s,r,a,n)||("parameters"!==o?Be(e,l,c,o,s,$e(r,o),n):ze(e,"error",i.malformedNode,"'parameters' is reserved and unused on operator nodes",$e(r,o),n,{operator:l.name})))}return Ke(e,l,c,a,n),l},Ue=(e,t,r,a)=>(e.operators.add(t.definition.name),{kind:"operator",name:t.definition.name,entry:t,params:{},path:r,order:a}),Ge=(e,t,r,a,n,o,i)=>"fallback"===r?(t.fallback=Me(e,a,$e(n,"fallback"),o+1),!0):"noCache"===r?(We(e,t,a,n,i),!0):"vars"===r&&(t.vars=gt(e,a,n,o,i),!0),We=(e,t,r,a,n)=>{!0===r?(t.noCache=!0,e.hasNoCache=!0):ze(e,"error",i.malformedNode,"'noCache' takes only the literal true — it is settled before the subtree runs",$e(a,"noCache"),n,"operator"===t.kind?{operator:t.name}:{})},Be=(e,t,r,a,n,o,s)=>{if(void 0===t.entry.definition.parameters[a]){const r=m(a,Object.keys(t.entry.definition.parameters));return void ze(e,"error",i.unknownNodeKey,`'${a}' is not a parameter of '${t.name}'${r?` — did you mean '${r}'?`:""}`,o,s,{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,i=o.resolution.perElement.length>0;let s;if(i){const a=r.find(e=>"as"===e.name&&"structural"===o.parameters.as?.evaluation&&"value"===e.kind);void 0!==a&&"value"===a.kind&&(s=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]=et(e,n,r,a))}if(i){void 0!==s&&e.scope.bindings.push(s);for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"===r&&(t.params[n.name]=et(e,n,r,a))}void 0!==s&&e.scope.bindings.pop()}Ze(e,t),He(e,t)},He=(e,t)=>{if("buildString"!==t.name)return;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 s=[],l=new Set;for(const t of a){if("named"!==t.kind||!t.body.startsWith("$"))continue;if(l.has(t.body))continue;const a=Ve(e,t.body,r.path,e.order++);"reference"===a.kind&&(e.nodeCount++,l.add(t.body),s.push({path:r.path,at:[t.body],node:a}))}0!==s.length&&(t.params.substitutions=_e(e,t,o,s))},_e=(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??$e(t.path,"substitutions"),order:r?.order??e.order++};return n.holes.push(...a),n},Xe=(e,t,r,a,n)=>{const o=(a,n,o="warning")=>ze(e,o,a,n,r.path,r.order,{operator:t.name});if("array"!==n.mode&&"dynamic"!==n.mode||a.some(e=>"named"===e.kind&&e.body.startsWith("$"))&&o(i.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;let t=!1;for(const r of a)"positional"===r.kind&&(r.index>=1&&r.index<=n.length?e.add(r.index):(t=!0,o(i.unboundToken,`'${r.raw}' binds to nothing and renders as its own text`)));const r=[];for(let t=1;t<=n.length;t++)e.has(t)||r.push(t);for(const e of r)o(i.unusedSubstitution,`substitution ${e} is never named by the template`);return void(r.length>0&&t&&o(i.tokenRenumber,`the tokens skip a number — renumber them to ${[...Array(n.length).keys()].map(e=>`%${e+1}`).join(", ")}`,"hint"))}if("object"===n.mode){const e=new Set;for(const t of a)"named"===t.kind&&(n.keys.has(t.body)?e.add(t.body):t.body.startsWith("$")||o(i.unboundToken,`'${t.raw}' binds to nothing and renders as its own text`));for(const t of n.keys)e.has(t)||o(i.unusedSubstitution,`substitution '${t}' is never named by the template`)}},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},et=(e,t,r,a)=>{if("lazyElements"===r||"race"===r){const r=nt(e,t,a);if(null!==r)return r}if("lazyEntries"===r){const r=ot(e,t,a);if(null!==r)return r}return"value"===t.kind?Me(e,t.value,t.path,a+1):tt(e,t,a)},tt=(e,t,r)=>{const{order:a,containerDepth:n}=rt(e,r),o=at(e,t.elements,t.basePath,t.offset,n),i=t.elements.some(e=>void 0===e);return kt(e,t.elements,o,!0,i,void 0,t.basePath,a)},rt=(e,t)=>{const r=e.order++,a=t+1;return a>e.maxDepth&&(e.maxDepth=a),{order:r,containerDepth:a}},at=(e,t,r,a,n)=>t.map((t,o)=>({key:o,rawChild:void 0===t?null:t,node:Me(e,void 0===t?null:t,$e(r,a+o),n+1)})),nt=(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:i,containerDepth:s}=rt(e,r),l=at(e,a,n,o,s);if(l.every(e=>"constant"===e.node.kind)){const t=a.some(e=>void 0===e);return kt(e,a,l,!0,t,void 0,n,i)}return{kind:"elements",nodes:l.map(e=>e.node),path:n,order:i}},ot=(e,t,r)=>{if("value"!==t.kind)return null;const a=t.value;if(!n(a)||f(a,e.recognizes))return null;const{order:o,containerDepth:i}=rt(e,r),{entries:s,vars:l,changed:c}=wt(e,a,t.path,i,o);if(s.every(e=>"constant"===e.node.kind))return kt(e,a,s,!1,c,l,t.path,o);const u={};for(const{key:e,node:t}of s)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,s)=>{const l=r=>{ze(e,"error",i.invalidAs,r,o,s,{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 s=r.slice(1),l="literal"===s,c=!l&&e.registry.fragments.has(s);for(const n in t)if(n!==r&&!p.has(n))return ze(e,"error",i.malformedNode,`'${n}' may not sit beside the shorthand key '${r}' — reserved modifiers only`,$e(a,n),o),Re(t,a,o);const u=t[r],d=$e(a,r);if(l){for(const r of["fallback","vars","noCache"])r in t&&ze(e,"warning",i.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,$e(a,r),o);return mt(e,t,u,!0,a,o)}if(c)return ht(e,t,s,u,a,n,o);const m=jr(e.registry,s),f=Ue(e,m,a,o);for(const i in t){const s=t[i];i!==r&&"//"!==i&&void 0!==s&&Ge(e,f,i,s,a,n,o)}const h=[];return lt(e,f,h,u,d,o),Ke(e,f,h,n,o),f},lt=(e,t,r,a,o,i)=>{if(Array.isArray(a))ut(e,t,r,a,o,i);else if(!n(a)||f(a,e.recognizes))ct(e,t,r,a,o,i);else for(const n in a){const s=a[n];"//"!==n&&void 0!==s&&Be(e,t,r,n,s,$e(o,n),i)}},ct=(e,t,r,a,n,o)=>{const i=v(t.entry.definition);null!==i?r.push({name:i,kind:"value",value:a,path:n}):dt(e,t,n,o)},ut=(e,t,r,a,n,o)=>{const i=t.entry.definition,s=h(i,a.length);if(null===s)return void pt(e,t,a,n,o);const l=i.positionalParams;for(let e=0;e<s.bound;e++)r.push({name:l[e],kind:"value",value:a[e],path:$e(n,e)});const{restAt:c}=s;null!==c&&r.push({name:i.restParam,kind:"slice",elements:0===c?a:a.slice(c),basePath:n,offset:c})},dt=(e,t,r,a)=>ze(e,"error",i.positionalArity,`'${t.name}' takes no positional arguments — use the named form`,r,a,{operator:t.name}),pt=(e,t,r,a,n)=>{const o=t.entry.definition.positionalParams;if(void 0===o)return void dt(e,t,a,n);const s=o.length;ze(e,"error",i.positionalArity,`'${t.name}' takes at most ${s} positional argument${1===s?"":"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?ze(e,"error",i.unknownNodeKey,`'${r}' is not a key of 'literal' — content goes in 'value'`,$e(n,r),o,{operator:"literal"}):ze(e,"warning",i.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,$e(n,r),o));if(!a)return ze(e,"error",i.malformedNode,"'literal' requires its content in 'value'",n,o,{operator:"literal"}),Re(t,n,o)}return Le(r,n,o)},ft=(e,t,r,a,n)=>{const o=t.fragment;if("string"!=typeof o)return ze(e,"error",i.malformedNode,"the 'fragment' value must be a literal string",r,n),Re(t,r,n);const s={kind:"fragmentCall",name:o,argumentsMode:"static",path:r,order:n};vt(e,s,a);for(const o in t){const l=t[o];"fragment"!==o&&"//"!==o&&void 0!==l&&("parameters"!==o?"fallback"!==o?"vars"!==o?"noCache"!==o?ze(e,"error",i.unknownNodeKey,`'${o}' is not a key of a fragment call — arguments live only in 'parameters'`,$e(r,o),n):We(e,s,l,r,n):s.vars=gt(e,l,r,a,n):s.fallback=Me(e,l,$e(r,"fallback"),a+1):yt(e,s,l,$e(r,"parameters"),a,n))}return s},ht=(e,t,r,a,o,s,l)=>{const c={kind:"fragmentCall",name:r,argumentsMode:"static",path:o,order:l};vt(e,c,s);for(const a in t){const n=t[a];a!==`$${r}`&&"//"!==a&&void 0!==n&&("fallback"===a&&(c.fallback=Me(e,n,$e(o,"fallback"),s+1)),"noCache"===a&&We(e,c,n,o,l),"vars"===a&&(c.vars=gt(e,n,o,s,l)))}return n(a)?yt(e,c,a,$e(o,`$${r}`),s,l):ze(e,"error",i.malformedNode,`fragments have no single-value or positional form — '$${r}' takes a named-arguments object`,$e(o,`$${r}`),l),c},vt=(e,t,r)=>{const{name:a,path:n,order:o}=t;e.fragmentNames.add(a);const s=e.registry.fragments.get(a);if(void 0===s){const t=m(a,e.registry.fragments.keys());return void ze(e,"error",i.unknownFragment,`'${a}' names no registered fragment${t?` — did you mean '${t}'?`:""}`,n,o,{suggestion:t})}t.entry=s,e.fragmentCalls.push({name:a,depth:r}),e.dataReads.push({kind:"call",fragment:s,path:n})},yt=(e,t,r,o,s,l)=>{if(void 0!==r){if(f(r,e.recognizes)||"string"==typeof r&&"reference"===a(r).kind)return t.argumentsMode="dynamic",t.parameters=Me(e,r,o,s+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,$e(o,t),s+1))}return void(t.parameters=a)}ze(e,"error",i.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one",o,l)}},gt=(e,t,a,o,s)=>{const l=$e(a,"vars");if(!n(t))return void ze(e,"error",i.invalidVars,"a 'vars' block must be an object of name → expression entries",l,s);const c={};for(const a in t){const n=t[a];if("//"===a||void 0===n)continue;const u=$e(l,a),d=r(a);d.ok?c[a]=Me(e,n,u,o+1):ze(e,"error",i.invalidName,`'${a}' is not a legal var name — ${d.reason}`,u,s)}return c},bt=(e,t,r,a,n)=>{const{entries:o,vars:i,changed:s}=wt(e,t,r,a,n);return kt(e,t,o,!1,s,i,r,n)},wt=(e,t,r,a,n)=>{let o,s=!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=m(c.slice(1),Pt(e));ze(e,"warning",i.unrecognizedIdentifier,`'${c}' is not a registered operator or fragment and will pass through as data${t?` — did you mean '$${t}'?`:""}`,$e(r,c),n,{suggestion:void 0===t?void 0:`$${t}`})}l.push({key:c,rawChild:u,node:Me(e,u,$e(r,c),a+1)})}else s=!0;else o=gt(e,u,r,a,n),s=!0;else s=!0}return{entries:l,vars:o,changed:s}},kt=(e,t,r,a,n,o,s,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&&ze(e,"warning",i.unreferencedVar,"this vars block declares names nothing in its scope references",$e(s,"vars"),l),Le(d||void 0!==o?u:t,s,l);const p={kind:"skeleton",skeleton:u,holes:c,path:s,order:l};return void 0!==o&&(p.vars=o),p},$t=(e,t)=>"constant"===t.kind?[]:"skeleton"===t.kind?t.holes.map(t=>({path:xe(t.path),node:t.node,...xt(e,t.node)})):[{path:xe(t.path),node:t,...xt(e,t)}],xt=(e,t)=>{const r=jt(e,t);return void 0===r?{}:{timeoutFallback:r}},jt=(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&&be(r.fallback,e.registry).constant?{value:r.fallback}:void 0}return t.entry?.timeoutFallback}},Pt=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 At(e.value);default:return"any"}},At=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"}},Dt=/*#__PURE__*/Object.freeze({parsePath:g,resolvePath:k,checkType:ie,checkConstraints:se,describeType:ee,renderText:I,isTruthy:M}),Nt=(e,t={})=>{St({artifact:e,context:t,varsFrames:[],iteratorFrames:[]},e.root),je(e.issues),e.hasErrors=Pe(e.issues)},Ct=(e,t,r,a,n,o,i={})=>{const s={severity:t,code:r,message:a,path:xe(n)};void 0!==i.operator&&(s.operator=i.operator),void 0!==i.fragment&&(s.fragment=i.fragment),void 0!==i.parameter&&(s.parameter=i.parameter),void 0!==i.suggestion&&(s.suggestion=i.suggestion),e.artifact.issues.push({issue:s,order:o})},St=(e,t)=>{switch(t.kind){case"constant":case"invalid":return;case"reference":return void Rt(e,t);case"skeleton":{const r=Jt(e,t.vars,t.path);for(const r of t.holes)St(e,r.node);return void Ut(e,r)}case"fragmentCall":return void Ft(e,t);case"elements":for(const r of t.nodes)St(e,r);return;case"entries":{const r=Jt(e,t.vars,t.path);for(const r in t.entries)St(e,t.entries[r]);return void Ut(e,r)}case"operator":return void Tt(e,t)}return t},qt=e=>"kind"in e&&"string"==typeof e.kind,Tt=(e,t)=>{const r=Jt(e,t.vars,t.path);void 0!==t.fallback&&St(e,t.fallback);const a=t.entry.definition,n=Mt(t);for(const[r,o]of a.resolution.entries){const a=t.params[r];void 0!==a?"constant"===a.kind&&null===a.value&&Et(t,r)||zt(e,n,r,o,a):o.required&&Ct(e,"error",i.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]):St(e,n)}if(o.length>0){const r={as:Oe(t),referenced:!1};e.iteratorFrames.push(r);for(const[,t]of o)St(e,t);e.iteratorFrames.pop(),r.referenced||Ct(e,"warning",i.deadBinding,`'${t.name}' binds ${null===r.as?"$element / $index":`$${r.as}`} but its 'each' references neither`,t.path,t.order,{operator:t.name})}Ut(e,r)},Et=(e,t)=>{const{definition:r,instanceDefaults:a}=e.entry;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},zt=(e,t,r,a,n)=>{if("constant"===n.kind){if(null===n.value&&!a.required&&!ae(a.type))return;const o=ie(n.value,a.type);if(!o.ok)return void Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r});if(void 0!==a.constraints){const o=pe(n.value,a.constraints,void 0!==a.elementNullPolicy);o.ok||Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r})}return}if("elements"===n.kind){const o=a.constraints?.length;return void(void 0!==o&&n.nodes.length!==o&&Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o} element${1===o?"":"s"}, received ${n.nodes.length}`,n.path,n.order,{...t.extra,parameter:r}))}if("structural"!==a.evaluation||"as"===r){if("operator"===n.kind||"fragmentCall"===n.kind&&void 0!==n.entry){const o=Ot(n);if(!$(o,a.type)){const a="operator"===n.kind?`'${n.name}'`:`fragment '${n.name}'`;Ct(e,"error",i.returnsMismatch,`${a} returns ${JSON.stringify(o)} — it can never satisfy '${t.label}.${r}'`,n.path,n.order,{...t.extra,parameter:r})}return}if("skeleton"===n.kind){const o=ie(Array.isArray(n.skeleton)?[]:{},a.type);o.ok||Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r})}}else Ct(e,"error",i.typeCheck,`'${t.label}.${r}' is structural — it requires a literal value`,n.path,n.order,{...t.extra,parameter:r})},Mt=e=>({label:e.name,extra:{operator:e.name}}),Ft=(e,t)=>{const r=Jt(e,t.vars,t.path);void 0!==t.fallback&&St(e,t.fallback);const a=t.entry?.parameters,n=void 0===t.parameters||qt(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 s=a[o],l=n?.[o];void 0!==l?zt(e,r,o,s,l):s.required&&Ct(e,"error",i.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=m(r,Object.keys(a));Ct(e,"error",i.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(qt(t.parameters))St(e,t.parameters);else for(const r in t.parameters)St(e,t.parameters[r]);Ut(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,Dt)}catch(r){return void Ct(e,"error",i.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;Ct(e,r.severity,i.operatorValidate,r.message,a?.path??t.path,t.order,{operator:t.name,...void 0!==r.parameter?{parameter:r.parameter}:{}})}},Rt=(e,t)=>{switch(t.namespace){case"data":return;case"vars":return void Vt(e,t);case"params":return void It(e,t);case"element":case"index":return void Qt(e,t,t.namespace)}},Vt=(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}}Ct(e,"error",i.unresolvedVar,`'${t.raw}': no var '${a??""}' is declared in scope`,t.path,t.order)},It=(e,t)=>{const r=e.context.fragmentParams;if(void 0===r)return void Ct(e,"error",i.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)||Ct(e,"error",i.unresolvedParam,`'${t.raw}': the fragment declares no parameter '${String(a)}'`,t.path,t.order)},Qt=(e,t,r)=>{for(let a=e.iteratorFrames.length-1;a>=0;a--){const n=e.iteratorFrames[a];if(Ae(n.as,r,t.binding))return void(n.referenced=!0)}Ct(e,"error",i.unresolvedBinding,`'${t.raw}' resolves against no enclosing iterator here`,t.path,t.order)},Jt=(e,t,r)=>{if(void 0===t)return null;const a={names:new Map,currentVar:null,edges:new Map},n=$e(r,"vars");for(const r in t){const o=t[r],s=$e(n,r);for(const t of e.varsFrames)if(t.names.has(r)){Ct(e,"warning",i.shadowedVar,`'${r}' shadows a var of the same name from an enclosing scope`,s,o.order);break}a.names.set(r,{node:o,declaredAt:s,order:o.order,referenced:!1})}e.varsFrames.push(a);for(const[t,r]of a.names)a.currentVar=t,St(e,r.node),a.currentVar=null;return a},Ut=(e,t)=>{if(null!==t){e.varsFrames.pop();for(const[r,a]of t.names)a.referenced||Ct(e,"warning",i.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);Ct(e,"error",i.varCycle,`'${r}' participates in a vars cycle — a var may not depend on itself`,a.declaredAt,a.order),n.add(r)}},Wt={capable:!1,effective:!1},Bt={capable:!0,effective:!0},Kt=e=>{const{effective:t}=Ht(e,e.root,!1);return je(e.issues),t},Ht=(e,t,r)=>{switch(t.kind){case"constant":case"reference":return Wt;case"invalid":return Bt;case"skeleton":return Yt(e,[...t.holes.map(e=>e.node),...Zt(t.vars)],r);case"elements":return Yt(e,t.nodes,r);case"entries":return Yt(e,[...Object.values(t.entries),...Zt(t.vars)],r);case"operator":return _t(e,t,wr(t.entry),r);case"fragmentCall":return _t(e,t,t.entry?.caches??!0,r)}return t},_t=(e,t,r,a)=>{const n=!0===t.noCache,o=Yt(e,Xt(t),a||n),i=r||o.capable;return n&&a?er(e,t,"'noCache' is redundant — an enclosing node already sets it"):n&&!i&&er(e,t,"'noCache' is dead — nothing beneath this node caches"),{capable:i,effective:!n&&(r||o.effective)}},Xt=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(...Zt(e.vars)),t},Yt=(e,t,r)=>{const a={capable:!1,effective:!1};for(const n of t){const{capable:t,effective:o}=Ht(e,n,r);a.capable||=t,a.effective||=o}return a},Zt=e=>void 0===e?[]:Object.values(e),er=(e,t,r)=>{const a={severity:"warning",code:i.uselessModifier,message:r,path:xe($e(t.path,"noCache"))};"operator"===t.kind?a.operator=t.name:a.fragment=t.name,e.issues.push({issue:a,order:t.order})};class tr{max;entries=new Map;constructor(e){this.max=e,rr(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(rr(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 rr=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError("LRU bound must be a positive integer")},ar=Symbol("fig-tree:lazy-handle"),nr="~",or=(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=or(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=or(e[r],t+1);if("json"!==a)return a}return"json"},ir=(e,t)=>sr(e,0,t)?t.join(""):void 0,sr=(e,t,r)=>{if(t>o)return!1;if(null===e)return cr(r,"n");if(void 0===e)return cr(r,"u");switch(typeof e){case"boolean":return cr(r,e?"t":"f");case"number":return lr(e,r);case"string":return cr(r,`s${e.length}:${e}`);case"object":break;default:return!1}if(Array.isArray(e)){r.push("[");for(const a of e)if(!sr(a,t+1,r))return!1;return cr(r,"]")}if(!n(e)||ar in e)return!1;r.push("{");for(const a in e)if(r.push(`s${a.length}:${a}`),!sr(e[a],t+1,r))return!1;return cr(r,"}")},lr=(e,t)=>Number.isNaN(e)?cr(t,"N"):e===1/0?cr(t,"I"):e===-1/0?cr(t,"J"):Object.is(e,-0)?cr(t,"#-0"):cr(t,`#${String(e)}`),cr=(e,t)=>(e.push(t),!0);class ur{deps;identity=new WeakMap;content=new tr(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=or(e,0);return"json"===t?JSON.stringify(e):"serializer"===t?ir(e,[nr]):void 0})(e),n=void 0===a?void 0:this.content.get(a),o=n??this.deps.compile(e),i={kind:"artifact",artifact:o};return void 0!==t&&this.identity.set(t,i),void 0!==a&&void 0===n&&!o.identityOnly&&o.holes.length>0&&this.content.set(a,o),i}}const dr=/*#__PURE__*/new Set(["type","required","default","description","metadata","constraints"]),pr=/*#__PURE__*/new Set(["expression","parameters","description","metadata"]),mr=(t,a,n)=>{const o=(...e)=>["fragments",t,...e],s=r(t);if(!s.ok)return void n(i.invalidName,`'${t}' is not a legal fragment name: ${s.reason}`,o());if(x.has(t))return void n(i.reservedName,`'${t}' is a reserved name and may not name a fragment`,o());if(!e(a))return void n(i.invalidDefinition,`fragment '${t}' must be a wrapper object: { expression, parameters?, description?, metadata? }`,o());if(!("expression"in a))return void n(i.invalidDefinition,`fragment '${t}' has no 'expression'`,o());for(const e of Object.keys(a))pr.has(e)||n(i.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(i.invalidDefinition,"'description' must be a string",o("description")):l.description=a.description),void 0!==a.metadata&&(e(a.metadata)?l.metadata=a.metadata:n(i.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=fr(e,t,o,n);void 0!==r&&(l.parameters[e]=r)}else n(i.invalidDefinition,"'parameters' must be a plain object",o("parameters"));return l},fr=(t,a,n,o)=>{const s=n("parameters",t),l=r(t);if(!l.ok)return void o(i.invalidName,`'${t}' is not a legal parameter name: ${l.reason}`,s);if(j.has(t))return void o(i.reservedName,`'${t}' is a reserved node key and may not name a parameter`,s);if(!e(a))return void o(i.invalidDefinition,`the declaration of '${t}' must be an object`,s);for(const e of Object.keys(a))dr.has(e)||o(i.invalidDefinition,`'${e}' is not a key of a parameter declaration`,[...s,e]);const c=a.type??"any";if(!oe(c))return void o(i.invalidDefinition,`'${t}' declares an unknown type`,[...s,"type"]);if(void 0!==a.required&&"boolean"!=typeof a.required)return void o(i.invalidDefinition,"'required' must be a boolean",[...s,"required"]);let u;if(void 0!==a.constraints){const e=ue(a.constraints);if(!e.ok)return void o(i.invalidDefinition,`'${t}' declares invalid constraints: expected ${e.expected}, got ${e.actual}`,[...s,"constraints"]);u=a.constraints}const d="default"in a;if(d&&!0===a.required)return void o(i.invalidDefinition,`'${t}' is declared required and also declares a default — the default could never apply`,[...s,"default"]);if(d){const e=ie(a.default,c);if(!e.ok)return void o(i.typeCheck,`the default for '${t}' does not satisfy its declared type: expected ${e.expected}, got ${e.actual}`,[...s,"default"]);if(void 0!==u){const e=se(a.default,u);if(!e.ok)return void o(i.typeCheck,`the default for '${t}' violates its declared constraints: expected ${e.expected}, got ${e.actual}`,[...s,"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},hr=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)},vr=(e,t)=>{const r=[],a=new Set,n=new Set,o=s=>{const l=r.indexOf(s);if(-1!==l){const e=[...r.slice(l),s],a=[...e].sort().join("\0");return n.has(a)||t(i.fragmentCycle,`fragment '${s}' reaches itself: ${e.join(" → ")} — recursion is not supported`,["fragments",s]),void n.add(a)}if(!a.has(s)){r.push(s);for(const t of e.get(s)?.fragmentCalls??[])o(t.name);r.pop(),a.add(s)}};for(const t of e.keys())o(t);return 0===n.size},yr=(e,t)=>{const r=new Set,a=n=>{if(r.has(n))return;r.add(n);const o=e.fragments.get(n),i=t.get(n);if(void 0===o||void 0===i)return;for(const e of i.fragmentCalls)a(e.name);const s=Te(i.own,i.fragmentCalls,e.fragments);o.nodeCount=s.nodeCount,o.maxDepth=s.maxDepth,o.dependencies=s.dependencies,o.identityOnly=s.identityOnly,o.caches=Kt(i),o.timeoutFallback=gr(i,e.fragments)};for(const e of t.keys())a(e)},gr=(e,t)=>{const{root:r,holes:a}=e;if(0===a.length)return;const n=[];for(const e of a){const r=br(e,t);if(void 0===r)return;n.push(r.value)}return"skeleton"===r.kind?{value:De(r.skeleton,r.holes,n)}:{value:n[0]}},br=(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},wr=e=>e.definition.cache&&!0!==e.instanceDefaults?.noCache,kr=["fallback","noCache"],$r=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:s}=n,l=new Map,c=(e,t,r)=>{const n=l.get(e);return void 0!==n?(a(i.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(i.invalidOptions,`operators[${t[1]}]${t.length>2?`[${t[2]}]`:""} is a function — factories must be called: httpOperators(client)`,t);if(!ve(e))return void a(i.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&&s.set(n,r))};return Array.isArray(t.operators)?t.operators.forEach((e,t)=>{Array.isArray(e)?e.forEach((e,r)=>{Array.isArray(e)?a(i.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(i.invalidOptions,"'operators' must be an array",["operators"]),void 0!==t.operatorDefaults&&xr(t.operatorDefaults,o,s,a),((t,r,a,n)=>{if(void 0===t)return;if(!e(t))return void n(i.invalidOptions,"'fragments' must be a plain object",["fragments"]);for(const[e,o]of Object.entries(t)){const t=mr(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],i=qe(n.expression,r,{basePath:["expression"]});a.body=i.root,o.set(e,i)}hr(r);for(const[e,t]of r.fragments){const r=o.get(e);Nt(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])}vr(o,n)&&yr(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 P({code:i.invalidOptions,message:a,path:t.path,...void 0!==t.operator?{operator:t.operator}:{},issues:e})})(r),n},xr=(t,r,a,n)=>{if(e(t))for(const[o,s]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(i.invalidOptions,`'operatorDefaults' keys are canonical names — use '${e}', not its alias '${o}'`,t,e):n(i.unknownOperator,`'${o}' names no registered operator`,t);continue}if(!e(s)){n(i.invalidOptions,`the defaults for '${o}' must be a plain object`,t,o);continue}let c=!0;for(const[e,r]of Object.entries(s)){const a=[...t,e];if(kr.includes(e)){"noCache"===e&&(!0!==r?(n(i.invalidOptions,"the 'noCache' modifier takes only the literal true",a,o),c=!1):l.definition.cache||(n(i.invalidOptions,`'noCache' on '${o}', which never caches — its definition does not declare 'cache: true'`,a,o),c=!1));continue}const s=l.definition.parameters[e];if(void 0===s){n(i.invalidOptions,`'${e}' names no declared parameter of '${o}' (nor 'fallback'/'noCache')`,a,o),c=!1;continue}if(s.required){n(i.invalidOptions,`'${e}' is a required parameter of '${o}' — operatorDefaults may only target optional parameters`,a,o),c=!1;continue}const u=ie(r,s.type);if(u.ok){if(void 0!==s.constraints){const t=se(r,s.constraints);t.ok||(n(i.typeCheck,`the default for '${o}.${e}' violates its declared constraints: expected ${t.expected}, got ${t.actual}`,a,o),c=!1)}}else n(i.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({...s}))}else n(i.invalidOptions,"'operatorDefaults' must be a plain object",["operatorDefaults"])},jr=(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},Pr="fig-tree:scope-settled",Or="fig-tree:request-expired",Ar="fig-tree:evaluation-timeout";class Dr{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?Pr:this.parent?.reason}get signal(){if(void 0===this.controller){const e=new AbortController;if(this.controller=e,this.settled)e.abort(Pr);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(Pr)))}}const Nr=(e,t)=>({get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:t.clock,settle:O}),Cr=(e,t,r)=>{const a=void 0===e?(()=>{const e=new AbortController;return{signal:e.signal,abort:t=>e.abort(t),settle:()=>e.abort(Pr)}})():(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(Pr)}}})(e),{signal:n}=a;let o;const i=new Promise((e,t)=>{o=t});i.catch(O);const s=()=>o(n.reason);n.aborted?s():n.addEventListener("abort",s,{once:!0});const l=void 0===t?void 0:setTimeout(()=>a.abort(r),Math.min(t,2147483647));return{signal:n,expiry:i,settle:()=>{void 0!==l&&clearTimeout(l),n.removeEventListener("abort",s),a.settle()}}},Sr=(e,t)=>Cr(e,t,Or),qr=(e,t)=>(r,a)=>{const n=(o=[e.operator,e.fingerprint,r],ir(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 i=await r();return await e.write(t,i,n),i})(t,n,a,e.note)},Tr=/*#__PURE__*/Object.freeze({}),Er=(e,t)=>!0!==t||!0===e.noCache?e:{...e,noCache:t};class zr{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 Mr={memo:(e,t)=>t()},Fr={note:O},Lr=Symbol("fig-tree:internal-error"),Rr=e=>Kr(`[fig-tree internal] ${e}`,Lr),Vr=e=>_r(e,Lr),Ir=Symbol("fig-tree:cancelled"),Qr=()=>Kr("[fig-tree] evaluation cancelled",Ir),Jr=e=>_r(e,Ir),Ur=(e,t,r)=>e.rootScope.aborted?Gr(e.rootScope.reason,t,r):e.abortScope.aborted?Qr():void 0,Gr=(e,t,r)=>e===Pr?Qr():Wr(e,xe(t),{operator:r}),Wr=(e,t,r={})=>{const{operator:a,ms:n}=r,o=e===Ar,s=void 0===n?"":`${n}ms `;return new P({code:o?i.timeout:i.aborted,message:o?`evaluation exceeded its ${s}timeout`:"evaluation was aborted by the caller",path:t,...void 0!==a?{operator:a}:{}})},Br=e=>A(e)&&(e.code===i.aborted||e.code===i.timeout),Kr=(e,t)=>{const r=new Error(e);return Hr(r,t),r},Hr=(e,t)=>{e[t]=!0},_r=(e,t)=>e instanceof Error&&!0===e[t],Xr=()=>performance.now(),Yr=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,...Zr(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,i)=>{const s=oa(e),l=ia(e),c={path:xe(e.path),kind:na(e),status:"value",...void 0!==o?{source:{fragment:o.fragment}}:{},...void 0!==s?{operator:s}:{},...void 0!==l?{ref:l}:{},...void 0!==i?.var?{var:i.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:i?.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}}},Zr=e=>ea(e.node).filter(t=>!e.seen.has(t)).map(e=>({entry:{path:xe(e.path),kind:na(e),status:"skipped"},order:e.order,index:0})),ea=e=>{switch(e.kind){case"operator":return[...Object.values(e.params).flatMap(ta),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{})];case"fragmentCall":return[...ra(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[]}},ta=e=>"elements"===e.kind||"entries"===e.kind?ea(e):[e],ra=e=>void 0===e?[]:aa(e)?[e]:Object.values(e),aa=e=>"string"==typeof e.kind,na=e=>{switch(e.kind){case"operator":return"operator";case"fragmentCall":return"fragment";case"reference":return"reference";case"skeleton":return"skeleton";default:return"literal"}},oa=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.name:void 0,ia=e=>"reference"===e.kind?e.raw:void 0,sa=(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(()=>Ka(n,a,{var:e})));return a},la=async(e,t,r,a,n)=>{const o={...r,params:"dynamic"===e.argumentsMode?await ua(e,t,a):ca(e,t,a),frame:n};delete o.scope,delete o.bindings;const i=await Ka(t.body,o);return void 0===i?null:i},ca=(e,t,r)=>{const a=e.parameters??{},n=new Map;for(const[o,i]of Object.entries(t.parameters)){const t=a[o],s=D(async()=>{if(void 0===t)return da(e,o,i,r);let a;try{a=await Ka(t,r)}catch(e){throw va(e,r.frame)}return pa(e,o,i,a,t.path,r)});n.set(o,()=>{const e=s();return e.catch(O),e})}return n},ua=async(t,r,a)=>{const n=t.parameters;let o;try{o=await Ka(n,a)}catch(e){throw va(e,a.frame)}if(!e(o))throw va(ma(t,i.typeCheck,`'parameters' must evaluate to an object, received ${fa(o)}`,n.path),a.frame);const s=new Map;for(const[e,i]of Object.entries(r.parameters)){const r=Object.hasOwn(o,e)?pa(t,e,i,o[e],n.path,a):da(t,e,i,a,n.path);s.set(e,()=>Promise.resolve(r))}return s},da=(e,t,r,a,n=e.path)=>{if(!r.required)return r.default??null;throw va(ma(e,i.missingRequired,`requires '${t}'`,n),a.frame)},pa=(e,t,r,a,n,o)=>{const s=void 0===a?null:a;if(null===s&&!r.required&&!ae(r.type))return r.default??null;if(!o.runtimeTypeCheck)return s;const l=ie(s,r.type);if(!l.ok)throw va(ma(e,i.typeCheck,`parameter '${t}': expected ${l.expected}, received ${l.actual}`,n),o.frame);if(void 0!==r.constraints){const a=se(s,r.constraints);if(!a.ok)throw va(ma(e,i.typeCheck,`parameter '${t}': expected ${a.expected}, received ${a.actual}`,n),o.frame)}return s},ma=(e,t,r,a)=>new P({code:t,message:`fragment '${e.name}' – ${r}`,path:xe(a)}),fa=e=>null===e?"null":Array.isArray(e)?"array":typeof e,ha=Symbol("fig-tree:anchored"),va=(e,t)=>!A(e)||_r(e,ha)?e:(Hr(e,ha),void 0===t||(e.fragment=t.fragment,e.fragmentPath=e.path,e.path=xe(t.callPath)),e);class ya 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 ga=e=>e instanceof ya,ba=(e,t,r)=>ka(Array.from({length:e},(e,a)=>wa(a,()=>t(a),r)),e),wa=async(e,t,r)=>{try{return{index:e,ok:!0,value:r(await t())}}catch(t){return{index:e,ok:!1,error:t}}},ka=(e,t)=>{const r=new Map(e.map((e,t)=>[t,e]));return{[ar]:!0,length:t,async*[Symbol.asyncIterator](){for(;r.size>0;){const e=await Promise.race(r.values());r.delete(e.index),yield e}}}},$a=e=>({[ar]:!0,evaluate:D(e)}),xa=e=>({[ar]:!0,evaluate:()=>Promise.resolve(e)}),ja=(e,t,r,a,n)=>$a(async()=>Pa(await Ka(e,n),t,r,a,n)),Pa=(e,t,r,a,n)=>{if(n.runtimeTypeCheck){const n=ie(e,a.type);if(!n.ok)throw Ca(t,r,n);if(null!==e&&void 0!==a.constraints){const n=pe(e,a.constraints,void 0!==a.elementNullPolicy);if(!n.ok)throw Ca(t,r,n)}}return a.truthiness?Ea(e,a.type):e},Oa=(e,t,r,a,n,o)=>{const i=Array.isArray(t)?t:[],s=Oe(r),l=new Map,c=t=>{const c=l.get(t);if(void 0!==c)return c;const u=(async()=>Pa(await Ka(e,((e,t,r,a)=>({...e,bindings:{parent:e.bindings,as:t,element:r,index:a}}))(o,s,i[t],t),{index:t}),r,a,n,o))();return u.catch(O),l.set(t,u),u};return{[ar]:!0,evaluate:c,settle:()=>ba(i.length,c,e=>e)}},Aa=(e,t)=>t.truthiness?M(e):e,Da=(e,t,r)=>{if("lazyElements"===t.evaluation&&"elements"===e.kind)return e.nodes.map((e,a)=>$a(async()=>Aa(await Ka(e,r,{index:a}),t)));if("race"===t.evaluation&&"elements"===e.kind)return((e,t,r)=>ba(e.length,r=>Ka(e[r],t,{index:r}),r))(e.nodes,r,e=>Aa(e,t));if("lazyEntries"===t.evaluation&&"entries"===e.kind){const a=sa(r,e.vars),n={};for(const[r,o]of Object.entries(e.entries))n[r]=$a(async()=>Aa(await Ka(o,a),t));return n}},Na=(e,t)=>{switch(t.evaluation){case"lazyElements":return e.map(e=>xa(Aa(e,t)));case"race":return((e,t)=>ba(e.length,t=>Promise.resolve(e[t]),t))(e,e=>Aa(e,t));case"lazyEntries":{const r={};for(const[a,n]of Object.entries(e))r[a]=xa(Aa(n,t));return r}case"lazy":return xa(e);default:return e}},Ca=(e,t,r)=>new P({code:i.typeCheck,message:`${e.name} – parameter '${t}': expected ${r.expected}, received ${r.actual}`,path:xe(e.path),operator:e.name}),Sa=(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],i=ie(o,n.type);if(!i.ok)throw Ca(e,a.selector,i);const s=a.table.find(e=>e.value===o);if(void 0===s)throw Rr(`no null-policy row for ${e.name}.${a.selector}`);return s.policy},qa=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},Ta=t=>Array.isArray(t)?t.includes(null):!!e(t)&&Object.values(t).includes(null),Ea=(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(M);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=M(a);return e}}return M(t)},za=async(e,t)=>{const{params:r,propagate:a}=await(async(e,t)=>{const{definition:r,instanceDefaults:a}=e.entry,{entries:n,whole:o,perElement:i}=r.resolution,s=[],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&&(s.push(r),l.push(Ka(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(()=>Ka(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]=ja(n,e,r,o,t));break;case"lazyElements":case"lazyEntries":case"race":{if(void 0===n)break;const e=Da(n,o,t);if(void 0!==e){d[r]=e;break}s.push(r),l.push(Ka(n,t));break}case"perElement":break;default:o.evaluation}}if(l.length>0)if(1===l.length){const e=l[0];c[s[0]]=N(e)?await e:e}else{const e=await Promise.all(l);s.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&&!ae(r.type))&&(void 0!==a&&Object.hasOwn(a,e)?c[e]=a[e]:"default"in r?c[e]=r.default===fe?t.data:r.default:delete c[e])}for(const[r,a]of o){if(Object.hasOwn(d,r))continue;let n=c[r];if(void 0===n)continue;const o=u?.[r];void 0!==o&&(n=await qa(n,a,o));const i="eager"!==a.evaluation&&"structural"!==a.evaluation;if(null===n&&ae(a.type)&&!i&&"propagate"===Sa(e,a,c))return{params:d,propagate:!0};if("propagate"===a.elementNullPolicy&&Ta(n))return{params:d,propagate:!0};n=Pa(n,e,r,a,t),d[r]=Na(n,a)}for(const[r,a]of i){if(void 0===a.over)throw Rr(`parameter '${r}' of '${e.name}' declares perElement without 'over'`);const n=e.params[r];void 0!==n&&(d[r]=Oa(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&&wr(e.entry),i=Fa(n,r),s=void 0===i?void 0:Sr(t.abortScope.signal,i),l=void 0===s?t:{...t,abortScope:Nr(s.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 zr(e.abortScope,e.options,r?{memo:qr({operator:t.name,fingerprint:t.fingerprint,note:a},e.cache)}:Mr,void 0===a?Fr:{note:a}))(l,n,o,c);try{return await Ma(e,t,r,u,s)}catch(r){throw La(r,e,t,s,i)}finally{s?.settle()}},Ma=async(e,t,r,a,n)=>{const o=Ur(t,e.path,e.name);if(void 0!==o)throw o;const i=Promise.resolve(e.entry.definition.evaluate(r,a));return void 0===n?Va(await i,e):(i.catch(O),Va(await Promise.race([i,n.expiry]),e))},Fa=(e,t)=>{const r=e.timeoutParam;if(null===r)return;const a=t[r];return"number"==typeof a&&a>0?a:void 0},La=(e,t,r,a,n)=>{if(Vr(e)||Jr(e))return e;const o=Ur(r,t.path,t.name);return void 0!==o?o:a?.signal.reason===Or?new ya(`request exceeded its ${String(n)}ms timeout`,{code:i.requestTimeout}):e},Ra=(e,t)=>{const r=e.fallback;if(void 0!==r)return()=>Ka(r,t);const a=e.entry.instanceDefaults;return void 0!==a&&Object.hasOwn(a,"fallback")?()=>a.fallback:void 0},Va=(e,t)=>{if(void 0===e)return null;if("number"==typeof e&&!Number.isFinite(e))throw new P({code:i.nonFiniteResult,message:`${t.name} – produced a non-finite number (${String(e)})`,path:xe(t.path),operator:t.name});if("object"==typeof(r=e)&&null!==r&&!0===r[ar])throw new P({code:i.escapedHandle,message:`${t.name} – returned a lazy handle instead of evaluating it`,path:xe(t.path),operator:t.name});var r;return e},Ia=(e,t)=>{if(A(e))return e;if(ga(e))return new P({code:e.code??i.operatorFailure,message:`${t.name} – ${e.message}`,path:xe(t.path),operator:t.name,...void 0!==e.errorData?{errorData:e.errorData}:{}});const r=e instanceof Error?e.message:String(e);return new P({code:i.operatorFailure,message:`${t.name} – ${r}`,path:xe(t.path),operator:t.name})},Qa=(e,t)=>0===e.segments.length?t.data:Wa(t.data,e.segments,e,t,"is absent from the evaluation data"),Ja=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 Rr(`'${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?Ba(o):Wa(o,a,e,t,`is absent from the value of '$vars.${r}'`)},Ua=async(e,t)=>{const r=t.params;if(void 0===r)throw Rr(`'${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]=Ba(await r())})),e}const o="string"==typeof a?r.get(a):void 0;if(void 0===o)throw Rr(`'${e.raw}': the fragment declares no parameter '${String(a)}' — the static gate should have refused it`);const i=await o();return 0===n.length?Ba(i):Wa(i,n,e,t,`is absent from the value of '$params.${String(a)}'`)},Ga=(e,t)=>{const r=e.namespace,a=((e,t,r)=>{for(let a=e;void 0!==a;a=a.parent)if(Ae(a.as,t,r))return a})(t.bindings,r,e.binding);if(void 0===a)throw Rr(`'${e.raw}': no enclosing iterator binds it — the static gate should have refused it`);return"index"===r?a.index:0===e.segments.length?Ba(a.element):Wa(a.element,e.segments,e,t,`is absent from '${e.raw.split(".")[0]}'`)},Wa=(e,t,r,a,n)=>{const o=k(e,t);if(o.found)return Ba(o.value);if(!a.strictDataPaths)return null;throw new P({code:i.missingDataPath,message:`'${r.raw}' ${n} (strictDataPaths)`,path:xe(r.path)})},Ba=e=>void 0===e?null:e,Ka=(e,t,r)=>void 0!==t.trace?Ha(e,t,t.trace,r):t.abortScope.aborted?Promise.reject(Ur(t,e.path)):_a(e,t),Ha=async(e,t,r,a)=>{const n=r.enter(e,t.traceParent,t.frame,a),o=Xr();try{if(t.abortScope.aborted)throw Ur(t,e.path);const a=await _a(e,{...t,traceParent:n});return r.settle(n,"value",{value:a,elapsed:Xr()-o}),a}catch(e){throw r.settle(n,Jr(e)?"cancelled":"failed",{...A(e)?{error:e}:{},elapsed:Xr()-o}),e}},_a=(e,t)=>{try{switch(e.kind){case"constant":return e.value;case"reference":return((e,t)=>{switch(e.namespace){case"data":return Qa(e,t);case"vars":return Ja(e,t);case"params":return Ua(e,t);case"element":case"index":return Ga(e,t)}})(e,t);case"skeleton":return Xa(e,t);case"operator":return(async(e,t)=>{const r=sa(Er(t,e.noCache),e.vars),a=e.entry.definition.deliversLazily?new Dr(r.abortScope):void 0,n=void 0===a?r:{...r,abortScope:a};try{try{return await za(e,n)}finally{a?.settle()}}catch(a){if(Vr(a)||Jr(a)||Br(a))throw a;const n=Ia(a,e),o=Ra(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(Vr(t)||Jr(t)||Br(t))throw t;const r=Ia(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 Rr(`fragment call '${e.name}' resolved to nothing — the static gate should have refused it`);const a=sa(Er(t,e.noCache),e.vars),n=new Dr(a.abortScope),o={fragment:e.name,callPath:t.frame?.callPath??e.path},i={...a,abortScope:n};try{try{return await la(e,r,i,a,o)}finally{n.settle()}}catch(r){if(Vr(r)||Jr(r)||Br(r))throw r;const n=va(r,o),{fallback:i}=e;if(void 0===i)throw n;try{return await Ka(i,a)}catch(e){if(Vr(e)||Jr(e)||Br(e))throw e;const r=va(e,t.frame);throw A(r)&&void 0===r.cause&&(r.cause=n),r}}})(e,t);case"elements":case"entries":throw Rr(`a '${e.kind}' parameter value reached the node dispatch — parameter resolution consumes these, and nothing else may hold one`);case"invalid":throw Rr("an invalid node reached evaluation — the static gate should have refused it")}}catch(e){return Promise.reject(e)}},Xa=async(e,t)=>{const r=t.rootBoundary,a=void 0===r?t:{...t,rootBoundary:void 0},n=sa(a,e.vars),o=e.holes.map(e=>void 0===r?Ka(e.node,n):r(()=>Ka(e.node,n),e.node)),i=o.some(N)?await Promise.all(o):o;return De(e.skeleton,e.holes,i)},Ya=Number.MAX_SAFE_INTEGER,Za=(e,t)=>{if(A(e))return e;const r=e instanceof Error?e.message:String(e);return new P({code:i.operatorFailure,message:r,path:t.path})},en=(e,t)=>{if(void 0===e.holePath)return e.holePath=t,e;const r=new P({...e,message:e.message,holePath:t});return r.stack=e.stack,r},tn=async(e,t,r)=>{const{timeout:a,signal:n}=t,o="report"===t.mode,s=e.holes.length>0,l=void 0!==a||void 0!==n?Cr(n,a,Ar):void 0,c=void 0!==l?((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}})(l.signal,l.settle):new Dr(void 0),u=void 0!==l&&void 0!==a&&e.timeoutShielded&&s,d=o?(()=>{const e=[];return{record:(t,r)=>{e.push({error:en(Za(t,r),r.path),order:r.node.order})},add:t=>{e.push({error:t,order:Ya})},emit:()=>[...e].sort((e,t)=>e.order-t.order).map(e=>e.error)}})():void 0,p=!0===t.trace?Yr(e.issues.map(e=>e.issue).filter(e=>"error"!==e.severity)):void 0,m=((e,t,r,a)=>({options:e,data:e.data??Tr,abortScope:r,rootScope:r,cache:t,strictDataPaths:e.strictDataPaths??!1,runtimeTypeCheck:e.runtimeTypeCheck??!0,...void 0!==a?{trace:a}:{}}))(t,r,c,p),f=s&&(void 0!==d||u)?on(e,d,u?l.expiry:void 0,p):void 0,h=void 0!==f&&"skeleton"!==e.root.kind,v=void 0===f||h?m:{...m,rootBoundary:f};try{if(c.aborted)throw Wr(c.reason,[]);const t=()=>h&&void 0!==f?f(()=>Ka(e.root,v),e.root):Ka(e.root,v),r=await(u||void 0===l?t():nn(t,l,a));return void 0!==d&&u&&an(l)&&d.add(Wr(Ar,[],{ms:a})),rn(r,d,p)}catch(e){if(void 0!==d&&A(e)&&e.code===i.timeout)return d.add(e),rn(null,d,p);throw void 0!==p&&A(e)&&void 0===e.trace&&(e.trace=p.finish()),e}finally{c.settle()}},rn=(e,t,r)=>({result:e,errors:t?.emit()??[],...void 0!==r?{trace:r.finish()}:{}}),an=e=>e.signal.aborted&&e.signal.reason===Ar,nn=(e,t,r)=>Promise.race([e(),t.expiry.catch(e=>{throw Wr(e,[],{ms:r})})]),on=(e,t,r,a)=>{const n=new Map(e.holes.map(e=>[e.node,e]));return(e,o)=>{const i=n.get(o);if(void 0===i)throw Rr(`the hole boundary was handed the node at ${JSON.stringify(xe(o.path))}, which is not one of the artifact's holes`);const s=void 0===t?Promise.resolve(e()):sn(e,i,t);if(void 0===r)return s;let l=!1;const c=s.then(e=>(l=!0,e));return Promise.race([c,r.catch(e=>{if(e!==Ar)throw Wr(e,[]);if(!l)return a?.noteOn(i.node,{type:"shielded-fallback"}),ln(i)})])}},sn=async(e,t,r)=>{try{return await e()}catch(e){if(Vr(e)||Jr(e)||Br(e))throw e;return r.record(e,t),null}},ln=e=>{if(void 0===e.timeoutFallback)throw Rr("a shielded artifact has a hole with no static fallback");return e.timeoutFallback.value},cn={hit:!1},un=e=>{if(void 0===e)return{maxSize:50,maxTime:1800};if(!n(e))throw pn("'cache' must be an object");const{store:t,maxSize:r,maxTime:a}=e;if(void 0!==t&&!dn(t))throw pn("'cache.store' must provide get, set, delete and clear methods");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw pn("'cache.maxSize' must be a positive integer");if(void 0!==a&&("number"!=typeof a||a<=0||Number.isNaN(a)))throw pn("'cache.maxTime' must be a positive number of seconds, or Infinity");return{...void 0!==t?{store:t}:{},maxSize:r??50,maxTime:a??1800}},dn=e=>"object"==typeof e&&null!==e&&["get","set","delete","clear"].every(t=>"function"==typeof e[t]),pn=e=>new P({code:i.invalidOptions,message:e,path:[]});class mn{store;own;maxTime;current=0;constructor(e){void 0===e.store?(this.own=new tr(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 cn}return n(r=t)&&"ft3"===r.fig&&"number"==typeof r.generation?t.generation<this.current||fn(t)?(this.drop(e),cn):{hit:!0,value:t.value}:cn;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(O)}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(O)}catch{}}}const fn=e=>void 0!==e.expiresAt&&e.expiresAt<=Date.now(),hn=e=>e===C?0:"number"==typeof e?1:2,vn=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=hn(r)-hn(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]}),yn=(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},gn=(e,t)=>{const r=[];return void 0!==t.maxDepth&&e.maxDepth>t.maxDepth&&r.push(bn(e.maxDepth,t.maxDepth)),void 0!==t.maxNodes&&e.nodeCount>t.maxNodes&&r.push({severity:"error",code:i.maxNodesExceeded,message:`the expression holds ${e.nodeCount} evaluable nodes — maxNodes is ${t.maxNodes}`,path:[]}),r},bn=(e,t)=>({severity:"error",code:i.maxDepthExceeded,message:`the expression nests ${e} levels deep — maxDepth is ${t}`,path:[]}),wn=(e,t,r)=>{const a=[...gn(e,t),...e.issues.map(r)];return void 0!==t.data&&a.push(...kn(e.dataReads,t.data)),a},kn=(e,t)=>{const r=new Map,a=new Map,n=[],o=(e,o,s,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(s.path);if(void 0===u&&a.set(s.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:i.missingDataPath,message:`'${S(o)}' is absent from the supplied sample data${d}`,path:xe(s.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},$n="...",xn=/*#__PURE__*/new Set(["propagate","value"]),jn=e=>{const t={};for(const[r,a]of Object.entries(e.parameters))t[r]=a.type??"any";const r=Pn(e.parameters,t,(t,r,a)=>{throw new P({code:t,message:r,path:a,operator:e.name})});return On(e,r)},Pn=(e,r,a)=>{const n=Object.entries(r).filter(([,e])=>t(e)).map(([e])=>e),o=new Map;for(const[s,l]of Object.entries(e)){if("function"!=typeof l.nullPolicy)continue;const e=["parameters",s,"nullPolicy"];if(1!==n.length){a(i.invalidNullPolicy,`a conditional 'nullPolicy' requires exactly one literal-union parameter in the definition — found ${n.length}`,e,s);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(i.invalidNullPolicy,`the conditional 'nullPolicy' threw during compilation for member ${JSON.stringify(t)}: ${String(r)}`,e,s),p=!1;break}if("string"!=typeof r||!xn.has(r)){a(i.invalidNullPolicy,`the conditional 'nullPolicy' must return 'propagate' or 'value' for every member — got ${JSON.stringify(r)} for ${JSON.stringify(t)}`,e,s),p=!1;break}d.push({value:t,policy:r})}p&&o.set(s,{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,i=n.type??"any",s=!0===n.truthiness&&ae(i)?"value":"propagate",l={type:Dn(i),required:n.required??!("default"in n),evaluation:n.evaluation??"eager",truthiness:n.truthiness??!1,nullPolicy:e??o??s};"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=Nn(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($n)?a.slice(3):null,o={[he]:!0,name:e.name,category:e.category,description:e.description,parameters:r,resolution:Cn(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?Dn(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=An(o),Sn(o)},An=e=>q(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)),Dn=e=>"string"==typeof e?e:t(e)?{literal:[...e.literal]}:[...e],Nn=t=>{if(Array.isArray(t))return t.map(Nn);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=Nn(a);return e}return t},Cn=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)}},Sn=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&&qn(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)},qn=t=>{Array.isArray(t)?(t.forEach(qn),Object.freeze(t)):e(t)&&(Object.values(t).forEach(qn),Object.freeze(t))},Tn=e=>{if(Array.isArray(e))return e;try{return g(e)}catch(e){throw new ya(e.message)}},En=(e,t)=>{if("string"!=typeof e)return[];try{return g(e),[]}catch(e){return[{severity:"error",parameter:t,message:e.message}]}},zn=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"}]:[],Mn=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`}]:[]},Fn=/*#__PURE__*/Mn("values"),Ln=/*#__PURE__*/Mn("input"),Rn=/*#__PURE__*/Mn("entries"),Vn=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"}]:[],In=(e,t)=>new ya(`${e} of nothing — the values array is empty${void 0!==t?`; ${t}`:""}`,{code:i.emptyAggregate}),Qn=e=>new ya(e,{code:i.typeCheck}),Jn=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),Un(r);return!t},Un=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},Gn=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)},Wn=(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=>X(r(e),a))},Bn={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:Bn,positionalParams:["...values"],returns:"boolean",validate:Vn,evaluate:({values:e,caseInsensitive:t})=>Wn(e,t)},Hn={name:"notEqual",alias:"!=",category:"comparison",description:'Are the values NOT all equal? The exact negation of equal (never "all distinct")',parameters:Bn,positionalParams:["...values"],returns:"boolean",validate:Vn,evaluate:({values:e,caseInsensitive:t})=>!Wn(e,t)},_n=(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(F(t,r))}}),Xn=/*#__PURE__*/_n("greaterThan",">","Is the first value strictly greater than the second?",e=>e>0),Yn=/*#__PURE__*/_n("greaterThanOrEqual",">=","Is the first value greater than or equal to the second?",e=>e>=0),Zn=/*#__PURE__*/_n("lessThan","<","Is the first value strictly less than the second?",e=>e<0),eo=/*#__PURE__*/_n("lessThanOrEqual","<=","Is the first value less than or equal to the second?",e=>e<=0),to={number:()=>0,string:()=>"",array:()=>[],object:()=>({})},ro=t=>"number"==typeof t?"number":"string"==typeof t?"string":Array.isArray(t)?"array":e(t)?"object":void 0,ao={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?Fn({values:e}):zn({values:e}),evaluate:({values:e,expect:t})=>{if(0===e.length){if(void 0===t)throw In("the sum","pin the mode with 'expect' to get its identity");return to[t]()}const r=t??ro(e[0]);if(void 0===r)throw Qn(`operands must be numbers, strings, arrays or objects — received ${ee(e[0])}`);const a=e.find(e=>ro(e)!==r);if(void 0!==a)throw Qn(`all operands must be ${r}s — received ${ee(a)}${void 0===t?" beside "+r+"s":""}`);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)}}},no={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},oo={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},io={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},so={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:Fn,evaluate:({values:e})=>e.reduce((e,t)=>e*t,1)},lo={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},co={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(K(Math.abs(e),t));return r*K(a,-t)})(e,t)},uo=(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)}),po=/*#__PURE__*/uo("floor","Round down toward negative infinity","The number to round down",Math.floor),mo=/*#__PURE__*/uo("ceil","Round up toward positive infinity","The number to round up",Math.ceil),fo=/*#__PURE__*/uo("abs","The absolute value","The number",Math.abs),ho=(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:zn,evaluate:({values:e})=>{const r=e;if(0===r.length)throw In(t);return r.reduce((e,t)=>a(F(t,e))?t:e)}}),vo=(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)}),yo={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?B(e):e.split(t);return r?a.map(Q):a}},go=e=>null!==e&&"object"==typeof e,bo=e=>Array.isArray(e.values)&&e.values.some(go)?[{severity:"error",parameter:"values",message:"a composite element renders as a placeholder, never as text — drill in, or join it explicitly"}]:[],wo={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=>[...Fn(e),...bo(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"}):go(e)&&r.trace.note({type:"render",token:a,rendered:"placeholder"}),I(e)}).join(t)},ko=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}`},$o={type:"array",description:"The collection iterated over; a null input is a type error"},xo={type:"string",required:!1,evaluation:"structural",description:"Rename the bindings: as: 'row' binds $row and $rowIndex"},jo={type:"array",required:!1,evaluation:"lazy",replacesNullAt:["input"],description:"Used as the collection when input evaluates to null — typically []"},Po={type:"any",evaluation:"perElement",over:"input",description:"The predicate, per element — a truthiness position, so null is falsy",truthiness:!0},Oo={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:fe,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})=>En(e,"path"),evaluate:({path:e,from:t,default:r},a)=>{const n=k(t,Tn(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 ya(`'${Ao(e)}' is missing (strictDataPaths)`,{code:i.missingDataPath});return null}},Ao=e=>"string"==typeof e?e:e.map(e=>String(e)).join("."),Do={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),...No(e)],evaluate:({entries:e},t)=>{const r={};for(const a of e){const e=I(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=I(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},Co=(e,t)=>new ya(`cannot convert ${ee(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:Fn,evaluate:({values:e})=>Jn(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:Fn,evaluate:({values:e})=>Jn(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:I(e);if(null!==a&&Object.hasOwn(t,a))return t[a].evaluate();if(void 0!==r)return r.evaluate();throw new ya(`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:Fn,evaluate:async({values:e})=>{for(const t of e){const e=await t.evaluate();if(null!==e)return e}return null}},Kn,Hn,Xn,Yn,Zn,eo,ao,no,so,oo,io,lo,co,po,mo,fo,/*#__PURE__*/ho("min","the minimum","The smallest of the values — numbers numerically, strings in codepoint order",e=>e<0),/*#__PURE__*/ho("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,i=void 0===o?t:void 0,s=[];for(const t of ge(e)){if("text"===t.kind){s.push({text:t.text,site:!1});continue}if(!("positional"===t.kind?void 0!==o&&t.index>=1&&t.index<=o.length:void 0!==i&&Object.hasOwn(i,t.body))){n.trace.note({type:"render",token:t.raw,rendered:"literal"}),s.push({text:t.raw,site:!1});continue}const e="positional"===t.kind?o[t.index-1]:i[t.body],a=I(e);go(e)&&n.trace.note({type:"render",token:t.raw,rendered:"placeholder"});const l=r?Q(a):a;""===l&&n.trace.note({type:"render",token:t.raw,rendered:"empty"}),s.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=G(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=W(o.text);e!==o.text&&t.push(a.token),o.text=e}}return t})(s))n.trace.note({type:"render",token:e,rendered:"gap-closed"});return s.map(e=>e.text).join("")}},yo,wo,/*#__PURE__*/vo("lower","Lowercase a string — Unicode default case mapping, locale-independent","The string to lowercase",e=>e.toLowerCase()),/*#__PURE__*/vo("upper","Uppercase a string — Unicode default case mapping, locale-independent","The string to uppercase",e=>e.toUpperCase()),/*#__PURE__*/vo("trim","Strip whitespace (the JS trim set) from both ends of a string","The string to trim",Q),{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?ko(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=ko(r);if(void 0!==o)throw new ya(o);const i=e=>{try{return new RegExp(t,r+e)}catch(e){throw new ya(`pattern does not compile: ${e.message}`)}};switch(a){case"test":return i("").test(e);case"extract":{const t=i("").exec(e);return null===t?n.evaluate():t[0]}case"match":return[...e.matchAll(i("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?B(e).length:e.length},{name:"map",category:"array",description:"Transform every element of an array",parameters:{input:$o,as:xo,nullInputDefault:jo,each:{type:"any",evaluation:"perElement",over:"input",description:"Evaluated per element, with $element and $index bound"}},positionalParams:["input","each"],returns:"array",validate:Ln,evaluate:({each:e})=>Gn(e.settle())},{name:"filter",category:"array",description:"Keep the elements of an array whose predicate is truthy",parameters:{input:$o,as:xo,nullInputDefault:jo,each:Po},positionalParams:["input","each"],returns:"array",validate:Ln,evaluate:async({input:e,each:t})=>{const r=await Gn(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:$o,as:xo,nullInputDefault:jo,each:Po,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:Ln,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:$o,as:xo,nullInputDefault:jo,each:Po},positionalParams:["input","each"],returns:"boolean",validate:Ln,evaluate:({each:e})=>Jn(e.settle(),!0)},{name:"every",category:"array",description:"True when every element satisfies the predicate",parameters:{input:$o,as:xo,nullInputDefault:jo,each:Po},positionalParams:["input","each"],returns:"boolean",validate:Ln,evaluate:({each:e})=>Jn(e.settle(),!1)},Oo,Do,{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 ya(`'${t}' is not a numeric string — use regex to extract a number from text`);return r}throw Co(t,"number");case"string":if(Array.isArray(t)||e(t))throw new ya(`cannot convert ${ee(t)} to string — a cast is not a render; use buildString or join`);if("object"==typeof t)throw Co(t,"string");return I(t);case"boolean":if("string"==typeof t){const e=t.trim().toLowerCase();if("true"===e)return!0;if("false"===e)return!1}return M(t);case"array":return Array.isArray(t)?t:[t]}}}].map(jn),qo=(e,t)=>{const r=((e,t)=>{const r={...e};for(const[e,a]of Object.entries(t)){if(void 0===a)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&&(o[e]=t);r[e]=o}return r})(null===e?{}:e.options,t);Uo(r);const a=To(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=$r({operators:r.operators??[So],...void 0!==r.operatorDefaults?{operatorDefaults:r.operatorDefaults}:{},...void 0!==r.fragments?{fragments:r.fragments}:{}});return{options:r,evaluation:a,registry:o,compileCache:new ur({compile:e=>Eo(e,o),probe:e=>be(e,o)})}},To=e=>{const t={...e};return delete t.operators,delete t.fragments,t},Eo=(e,t)=>{const r=qe(e,t);return Nt(r),r.hasNoCache&&Kt(r),r};class zo{state;results;version=Y;constructor(e={}){this.state=qo(null,e),this.results=new mn(un(e.cache))}updateOptions(e={}){const t=qo(this.state,e),r=un(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:yn(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:vn(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:Qo(this.state.evaluation,t),a=Eo(e,this.state.registry),n=wn(a,r,e=>e.issue);return{valid:!n.some(e=>"error"===e.severity),issues:n,timeoutShielded:a.timeoutShielded}}getDependencies(e){return vn(qe(e,this.state.registry).dependencies)}isEvaluable(e){const t=qe(e,this.state.registry);return t.holes.length>0||t.hasErrors}evaluate(e,t){const{state:r}=this;return Mo(r.evaluation,this.results,e,t,()=>r.compileCache.resolve(e),()=>Eo(e,r.registry))}compile(e){const{state:t}=this;return Ro(e,t.compileCache.resolve(e),t.evaluation,t.registry,this.results)}}const Mo=async(e,t,r,a,n,o)=>{const i=void 0===a?e:Qo(e,a),s="report"===i.mode,l=s||!0===i.trace,c=n(),u="inert"===c.kind&&!0===i.trace?{kind:"artifact",artifact:o()}:c;if("inert"===u.kind){if(void 0!==i.maxDepth&&u.depth>i.maxDepth){const e=bn(u.depth,i.maxDepth);if(!s)throw Wo(e,[e]);return Vo(null,[Wo(e)])}return l?Vo(r,[]):r}const{artifact:d}=u;if(d.hasErrors||void 0!==i.maxDepth||void 0!==i.maxNodes){const e=[...gn(d,i),...d.issues.map(e=>e.issue)],t=e.filter(e=>"error"===e.severity);if(t.length>0){if(!s)throw Wo(t[0],e);return Vo(null,t.map(e=>Wo(e)))}}const p=await tn(d,i,t);return l?p:p.result};let Fo;class Lo{#t;#r;#a;#n;#o;#i;#s;constructor(e,t,r,a,n){this.#t=e,this.#r=t,this.#a=r,this.#n=a,this.#o=n,Fo??=(e,t)=>{if("object"!=typeof e||null===e||!(#r in e))return;const r=void 0===t?e.#a:Qo(e.#a,t);return{expression:e.#t,artifact:e.#l(),options:r}}}get expression(){return this.#t}get issues(){return this.#s??=this.#l().issues.map(e=>e.issue)}get hasErrors(){return this.#l().hasErrors}evaluate(e){return Mo(this.#a,this.#o,this.#t,e,()=>this.#r,()=>this.#l())}getDependencies(){return vn(this.#l().dependencies)}#l(){return"artifact"===this.#r.kind?this.#r.artifact:this.#i??=Eo(this.#t,this.#n)}}const Ro=(e,t,r,a,n)=>new Lo(e,t,r,a,n),Vo=(e,t)=>({result:e,errors:t}),Io=/*#__PURE__*/new Set(Object.keys({data:0,signal:0,timeout:0,mode:0,trace:0})),Qo=(e,t)=>{let r;for(const a in t){const n=t[a];if(void 0!==n){if(!Io.has(a))throw Jo(a);r??={...e},r[a]=n}}return void 0===r?e:(Uo(t),r)},Jo=e=>new P({code:i.invalidOptions,message:`'${e}' is not a per-call option — a call may supply data, signal, timeout, mode and trace; configure the rest at construction or via updateOptions()`,path:[]}),Uo=e=>{const{timeout:t,signal:r}=e;if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new P({code:i.invalidOptions,message:"'timeout' must be a positive number of milliseconds",path:[]});if(void 0!==r&&!Go(r))throw new P({code:i.invalidOptions,message:"'signal' must be an AbortSignal",path:[]})},Go=e=>"object"==typeof e&&null!==e&&"boolean"==typeof e.aborted&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Wo=(e,t)=>new P({code:e.code,message:e.message,path:e.path,...void 0!==e.operator?{operator:e.operator}:{},...void 0!==t?{issues:t}:{}}),Bo=/[a-z]Default$/,Ko=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),Ho=/*#__PURE__*/new Set(me),_o=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),Xo=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),Yo=(e,t)=>{const[r]=e,a=e.length-1,n=a>0?`${r.message} (+ ${a} more issue${1===a?"":"s"})`:r.message;throw new P({code:i.invalidDefinition,message:n,path:r.path,...void 0!==t?{operator:t}:{},issues:e})};function Zo(t){if(ve(t))return t;const a=[],n=e(t)?t.name:void 0,o="string"==typeof n?n:void 0,s=(e,t,r,n)=>{a.push({severity:"error",code:e,message:t,path:r,...void 0!==o?{operator:o}:{},...void 0!==n?{parameter:n}:{}})};e(t)||(s(i.invalidDefinition,"a definition must be a plain object",[]),Yo(a));const l=t;"string"!=typeof l.name&&s(i.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof l.description&&""!==l.description||s(i.invalidDefinition,"'description' is required and must be non-empty",["description"]),e(l.parameters)||s(i.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof l.evaluate&&s(i.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),a.length>0&&Yo(a,o),"string"!=typeof l.category?s(i.invalidDefinition,`'category' is required and must be one of ${[...Ho].join(", ")}`,["category"]):Ho.has(l.category)||s(i.invalidDefinition,`'${l.category}' is not a category — expected one of ${[...Ho].join(", ")}`,["category"]),void 0!==l.alias&&"string"!=typeof l.alias&&s(i.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==l.cache&&!0!==l.cache&&s(i.invalidDefinition,"'cache' must be the literal true",["cache"]),void 0===l.metadata||e(l.metadata)||s(i.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===l.positionalParams||Array.isArray(l.positionalParams)&&!l.positionalParams.some(e=>"string"!=typeof e)||s(i.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==l.timeoutParam&&"string"!=typeof l.timeoutParam&&s(i.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==l.validate&&"function"!=typeof l.validate&&s(i.invalidDefinition,"'validate' must be a function",["validate"]),void 0===l.returns||oe(l.returns)||s(i.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const c=(e,t,r)=>{e===fe?s(i.invalidDefinition,"the EvaluationData sentinel is legal only as a parameter 'default'",t,r):Array.isArray(e)&&e.forEach((e,a)=>{e===fe&&c(e,[...t,a],r)})};for(const[e,t]of Object.entries(l))"parameters"!==e&&"metadata"!==e&&c(t,[e]);const u=(e,t)=>{const a=r(e);a.ok?x.has(e)&&s(i.reservedName,`'${e}' is a reserved name`,t):s(i.invalidName,`'${e}': ${a.reason}`,t)};"string"==typeof l.name&&u(l.name,["name"]),"string"==typeof l.alias&&u(l.alias,["alias"]);const d=l.parameters,p={};for(const[t,a]of Object.entries(d)){const n=["parameters",t],o=r(t);o.ok?j.has(t)&&s(i.reservedName,`'${t}' is a reserved node key and cannot name a parameter`,n,t):s(i.invalidName,`'${t}': ${o.reason}`,n,t),e(a)?p[t]=a:s(i.invalidDefinition,`the declaration for '${t}' must be a plain object`,n,t)}const m={};for(const[t,r]of Object.entries(p)){const a=["parameters",t],n=e=>[...a,e],o=r;for(const[e,r]of Object.entries(o))"default"!==e&&"metadata"!==e&&c(r,n(e),t);let l=!0;void 0===o.type||oe(o.type)||(s(i.invalidDefinition,"'type' must be a metadata-vocabulary type",n("type"),t),l=!1),l&&(m[t]=o.type??"any");let u=!1;if(void 0!==o.constraints){const e=ue(o.constraints);e.ok?u=!0:s(i.invalidDefinition,`'constraints' is malformed: expected ${e.expected}, got ${e.actual}`,n("constraints"),t)}void 0!==o.required&&"boolean"!=typeof o.required&&s(i.invalidDefinition,"'required' must be a boolean",n("required"),t),void 0!==o.description&&"string"!=typeof o.description&&s(i.invalidDefinition,"'description' must be a string",n("description"),t),void 0===o.metadata||e(o.metadata)||s(i.invalidDefinition,"'metadata' must be a plain object",n("metadata"),t);const d="default"in o;if(d&&!0===o.required&&s(i.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",n("default"),t),d&&o.default!==fe){const e=m[t];if(void 0!==e){const r=ie(o.default,e);if(r.ok){if(u&&void 0!==o.constraints){const e=se(o.default,o.constraints);e.ok||s(i.typeCheck,`'default' violates the declared constraints: expected ${e.expected}, got ${e.actual}`,n("default"),t)}}else s(i.typeCheck,`'default' does not satisfy the declared type: expected ${r.expected}, got ${r.actual}`,n("default"),t)}}if(void 0===o.evaluation||Ko.has(o.evaluation)||s(i.invalidDefinition,`'evaluation' must be one of ${[...Ko].join(", ")}`,n("evaluation"),t),void 0!==o.truthiness&&"boolean"!=typeof o.truthiness&&s(i.invalidDefinition,"'truthiness' must be a boolean",n("truthiness"),t),void 0!==o.over&&"string"!=typeof o.over&&s(i.invalidDefinition,"'over' must be a parameter name",n("over"),t),void 0===o.replacesNullAt||Array.isArray(o.replacesNullAt)&&!o.replacesNullAt.some(e=>"string"!=typeof e)||s(i.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",n("replacesNullAt"),t),void 0!==o.nullPolicy){const e=o.nullPolicy;"function"==typeof e||xn.has(e)||s(i.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",n("nullPolicy"),t);const r=m[t];void 0===r||ae(r)||s(i.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",n("nullPolicy"),t),!0===o.truthiness&&"propagate"===e&&s(i.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",n("nullPolicy"),t)}if(void 0!==o.elementNullPolicy){xn.has(o.elementNullPolicy)||s(i.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",n("elementNullPolicy"),t);const e=m[t];void 0===e||Xo(e)||s(i.invalidNullPolicy,"'elementNullPolicy' applies to container parameters only",n("elementNullPolicy"),t)}}if(Array.isArray(l.positionalParams)&&l.positionalParams.every(e=>"string"==typeof e)){const e=new Set,t=l.positionalParams;t.forEach((r,a)=>{const n=r.startsWith($n),o=n?r.slice(3):r;n&&a!==t.length-1&&s(i.invalidDefinition,`the rest entry '${r}' must be the last positional entry`,["positionalParams",a]),o in p||s(i.invalidDefinition,`positional entry '${r}' names no declared parameter`,["positionalParams",a]),e.has(o)&&s(i.invalidDefinition,`duplicate positional entry '${r}'`,["positionalParams",a]),e.add(o)})}for(const[e,t]of Object.entries(p)){const r=["parameters",e],a="perElement"===t.evaluation;if(void 0!==t.over&&"string"==typeof t.over)if(a){const a=t.over;if(a in p&&a!==e){const t=m[a];void 0===t||_o(t)||s(i.invalidDefinition,`the 'over' target '${a}' must admit an array`,[...r,"over"],e)}else s(i.invalidDefinition,`'over' names no sibling parameter ('${a}')`,[...r,"over"],e)}else s(i.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...r,"over"],e);else a&&s(i.invalidDefinition,"evaluation: 'perElement' requires 'over' to name the iterated sibling",[...r,"evaluation"],e)}for(const[e,t]of Object.entries(p)){if(void 0===t.replacesNullAt)continue;if(!Array.isArray(t.replacesNullAt)||t.replacesNullAt.some(e=>"string"!=typeof e))continue;const r=["parameters",e,"replacesNullAt"];"lazy"!==t.evaluation&&s(i.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",r,e);(t.required??!("default"in t))&&s(i.invalidDefinition,"a 'replacesNullAt' holder must be optional",r,e),"default"in t&&s(i.invalidDefinition,"a 'replacesNullAt' holder may not carry a 'default' — it is presence-sensitive by construction",r,e),t.replacesNullAt.forEach((t,a)=>{t===e?s(i.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...r,a],e):t in p||s(i.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...r,a],e)})}for(const[e,t]of Object.entries(p))Bo.test(e)&&"lazy"!==t.evaluation&&s(i.invalidDefinition,`'${e}' is named for the '…Default' family, so it must declare evaluation: 'lazy' — add 'replacesNullAt', read it as a LazyValue in the body, or rename it`,["parameters",e,"evaluation"],e);const f=Pn(p,m,s);if("string"==typeof l.timeoutParam){void 0===p[l.timeoutParam]?s(i.invalidDefinition,`'timeoutParam' names no declared parameter ('${l.timeoutParam}')`,["timeoutParam"]):"integer"!==m[l.timeoutParam]&&s(i.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return a.length>0&&Yo(a,o),On(l,f)}const ei=e=>new ya(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),ti=(e,t)=>{const r=t instanceof Error?t.message:String(t),a=t??{},n={driver:e};for(const e of["code","table","column","constraint"])"string"==typeof a[e]&&(n[e]=a[e]);return new ya(`${e}: ${r}`,{errorData:n})},ri=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class ai{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new ya("FetchClient(): this runtime has no global fetch — pass one, new FetchClient(myFetch), or use another client such as new AxiosClient(axios)");this.supplied=e}request=async e=>{const t=this.supplied??globalThis.fetch,r=await t.call(globalThis,e.url,{method:e.method.toUpperCase(),headers:e.headers,...void 0!==e.body?{body:JSON.stringify(e.body)}:{},signal:e.signal}),a=await r.text();if(!r.ok)throw ei({status:r.status,statusText:r.statusText,url:r.url||e.url,payload:ii(a)});return oi(a,r.url||e.url,r.status)}}class ni{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new ya("AxiosClient(axios): pass the axios import itself — new AxiosClient(axios)")}request=async e=>{try{const t=await this.axios({url:e.url,method:e.method,headers:e.headers,...void 0!==e.body?{data:e.body}:{},signal:e.signal});return""===t.data||void 0===t.data?null:t.data}catch(t){if(this.axios.isAxiosError(t)&&t.response)throw ei({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const oi=(e,t,r)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new ya(`response was not JSON (${r}): ${t}`,{errorData:{status:r,url:t,response:ri(e)}})}},ii=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return ri(e)}},si=/^https?:\/\//i,li=(e,t,r)=>{const a=si.test(e)?e:ci(r,e),n=ui(t),o=""===n?a:`${a}${a.includes("?")?"&":"?"}${n}`;try{new URL(o)}catch{throw new ya(`'${o}' is not a valid URL`,{code:i.typeCheck})}return o},ci=(e,t)=>{if(void 0===e||""===e)throw new ya(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:i.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},ui=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))null!=a&&t.append(r,mi(a,`query['${r}']`,"query"));return t.toString()},di=(...e)=>{const t={};for(const r of e)if(void 0!==r)for(const[e,a]of Object.entries(r))null!=a?t[e]=mi(a,`headers['${e}']`,"header"):delete t[e];return t},pi=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),mi=(e,t,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return I(e);throw new ya(`${t} is ${ee(e)} — a ${r} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:i.typeCheck})},fi=e=>({method:e.method,url:e.url,headers:Object.fromEntries(Object.entries(e.headers).sort(([e],[t])=>e<t?-1:e>t?1:0)),...void 0!==e.body?{body:e.body}:{}}),hi=t=>Array.isArray(t)?t.length>0:e(t)?Object.keys(t).length>0:null!=t,vi=(e,t)=>{if(void 0===t)return e;const r=k(e,Tn(t));return r.found?void 0===r.value?null:r.value:null},yi=(t,r)=>{if(!e(t))throw new ya("a row was not an object");const a=Object.values(t);if(1!==a.length)throw new ya(`shape: '${r}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:i.typeCheck});return a[0]},gi={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},bi={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},wi=e=>({name:"http",category:"io",description:"One HTTP request — GET or POST — returning the parsed JSON response",parameters:{url:{type:"string",description:"A full http(s) URL is used verbatim; anything else — including an empty string — joins http.baseEndpoint"},method:{type:{literal:["get","post"]},default:"get",description:"Lowercase; the mutating verbs are deliberately absent — an expression is a read"},query:{type:"object",required:!1,elementNullPolicy:"value",description:"Query-string pairs; a null value omits its pair, a composite one is an error"},body:{type:["string","number","boolean","array","object"],required:!1,description:"The JSON payload; a whole-null body means NO body, while nulls inside one are JSON nulls"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over the http.headers option per key; a null value removes an inherited pair"},returnPath:bi,timeout:gi},positionalParams:["url"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e,method:t,body:r})=>[...En(e,"returnPath"),...xi(t,r)],evaluate:async({url:t,method:r,query:a,body:n,headers:o,returnPath:s},l)=>{if("get"===r&&void 0!==n)throw new ya("a GET carries no body — did you mean method: 'post'?",{code:i.typeCheck});const c={method:r,url:li(t,a,l.options.http?.baseEndpoint),headers:di(pi(void 0!==n),l.options.http?.headers,o),...void 0!==n?{body:n}:{}},u=await l.cache.memo(fi(c),()=>(Oi(l,c),e.request({...c,signal:l.signal})));return vi(u,s)}}),ki=t=>({name:"graphQL",category:"io",description:"One GraphQL query — a POST of { query, variables } — returning the data field",parameters:{query:{type:"string",description:"The GraphQL document — the protocol’s own word, as sql.query is"},variables:{type:"object",required:!1,elementNullPolicy:"value",description:"Query variables; a null value is CARRIED as JSON null, a nullable argument being meaningful GraphQL"},url:{type:"string",required:!1,description:"Per-node endpoint override; unset means the graphQL.endpoint option"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over http.headers then graphQL.headers; a null value removes a pair"},returnPath:bi,timeout:gi},positionalParams:["query","variables"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e})=>En(e,"returnPath"),evaluate:async({query:r,variables:a,url:n,headers:o,returnPath:i},s)=>{const l=n??s.options.graphQL?.endpoint;if(void 0===l)throw new ya("no endpoint — supply url, or set the graphQL.endpoint option");const c={method:"post",url:li(l,void 0,s.options.http?.baseEndpoint),headers:di(pi(!0),s.options.http?.headers,s.options.graphQL?.headers,o),body:{query:r,...hi(a)?{variables:a}:{}}},u=await s.cache.memo(fi(c),async()=>(Oi(s,c),(t=>{if(!e(t))throw new ya("the GraphQL response was not an object");const r=t.errors;if(Array.isArray(r)&&r.length>0){const e=r[0]?.message;throw new ya(`the GraphQL response carried ${r.length} error${1===r.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:r}})}if(!("data"in t))throw new ya("the GraphQL response carried neither data nor errors");return t.data??null})(await t.request({...c,signal:s.signal}))));return vi(u,i)}}),$i=e=>({name:"sql",category:"io",description:"One SQL query against the registered connection. Expressions are READS — give the connection a read-only role and run mutations host-side",parameters:{query:{type:"string",description:"SQL text with the driver’s own placeholders — FigTree never parses SQL"},values:{type:["array","object"],required:!1,elementNullPolicy:"value",description:"Bind values — positional as an array, named as an object; a null binds SQL NULL"},shape:{type:{literal:["rows","firstRow","column","firstValue"]},default:"rows",description:"rows: every row object; firstRow: the first; column: one column’s values; firstValue: one scalar"},noRowDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The answer when firstRow / firstValue find no row — never for rows / column, never on failure"},timeout:gi},positionalParams:["query","...values"],timeoutParam:"timeout",cache:!0,returns:"any",evaluate:async({query:t,values:r,shape:a,noRowDefault:n},o)=>{const i={text:t,...hi(r)?{values:r}:{}};return(async(e,t,r)=>{switch(t){case"rows":return e;case"firstRow":return 0===e.length?r.evaluate():e[0];case"column":return e.map(e=>yi(e,"column"));case"firstValue":return 0===e.length?r.evaluate():yi(e[0],"firstValue")}})(await o.cache.memo(i,()=>(o.trace.note({type:"query",text:i.text}),e.query({...i,signal:o.signal}))),a,n)}}),xi=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],ji=(e=new ai)=>[jn(wi(e)),jn(ki(e))],Pi=e=>[jn($i(e))],Oi=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class Ai{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new ya("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new ya("postgres takes positional binds ($1, $2, …) — an object of named binds needs a driver that supports them");try{const t=await this.client.query({text:e.text,...void 0!==e.values?{values:e.values}:{}});return t?.rows??[]}catch(e){throw ti("postgres",e)}}}class Di{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new ya("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw ti("sqlite",e)}}}const Ni=e=>Ci(e,0,new Set),Ci=(e,t,r)=>{if(null===e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e&&Number.isFinite(e)&&!Object.is(e,-0))return e;if("object"!=typeof e)return Si(e);if(!Array.isArray(e)&&!n(e))return qi(e);if(r.has(e))return"[circular]";if(t>=o)return"[too deep]";r.add(e);const a=Array.isArray(e)?Array.from(e,e=>Ci(e,t+1,r)):Object.fromEntries(Object.entries(e).map(([e,a])=>[e,Ci(a,t+1,r)]));return r.delete(e),a},Si=e=>{switch(typeof e){case"function":return""===e.name?"[function]":`[function ${e.name}]`;case"symbol":return`[${String(e)}]`;case"bigint":return`[bigint ${e}]`;case"number":return Object.is(e,-0)?"[-0]":`[${e}]`;default:return"[undefined]"}},qi=e=>{const t=Ti(e);try{const r=e.toJSON;if("function"==typeof r){const a=r.call(e);if("string"==typeof a)return`[${t} ${a}]`}}catch{}return`[${t}]`},Ti=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},Ei=e=>{const t=new Map;for(const r of e.holes)void 0!==r.timeoutFallback&&t.set(r.node,r.timeoutFallback);const r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])),a=e=>{const r=t.get(e);return void 0===r?{}:{timeoutFallback:Ni(r.value)}},n=e=>{const t={order:e.order,kind:e.kind,path:xe(e.path)},o="vars"in e&&void 0!==e.vars?{vars:r(e.vars)}:{};switch(e.kind){case"constant":return{...t,kind:e.kind,value:Ni(e.value)};case"reference":return{...t,kind:e.kind,reference:E(e.binding??e.namespace,e.segments),authored:e.raw,...void 0===e.binding?{}:{binding:e.binding}};case"operator":return{...t,kind:e.kind,...o,operator:e.name,params:r(e.params),...void 0===e.fallback?{}:{fallback:n(e.fallback)},...a(e),...void 0===e.noCache?{}:{noCache:e.noCache},...void 0===e.entry.instanceDefaults?{}:{instanceDefaults:Object.keys(e.entry.instanceDefaults)}};case"fragmentCall":return{...t,kind:e.kind,...o,fragment:e.name,resolved:void 0!==e.entry,argumentsMode:e.argumentsMode,...void 0===e.parameters?{}:{parameters:"dynamic"===e.argumentsMode?n(e.parameters):r(e.parameters)},...void 0===e.fallback?{}:{fallback:n(e.fallback)},...a(e),...void 0===e.noCache?{}:{noCache:e.noCache}};case"skeleton":{const r=De(e.skeleton,e.holes,e.holes.map(()=>"<hole>"));return{...t,kind:e.kind,...o,shape:Ni(r),holes:e.holes.map(e=>({at:[...e.at],node:n(e.node)}))}}case"elements":return{...t,kind:e.kind,elements:e.nodes.map(n)};case"entries":return{...t,kind:e.kind,...o,entries:r(e.entries)};case"invalid":return{...t,kind:e.kind,raw:Ni(e.raw)}}};return n(e.root)},zi=(e,t)=>{const r=(a=e,n=t,Fo?.(a,n));var a,n;if(void 0===r)throw new TypeError("inspect() takes a CompiledExpression — the handle fig.compile() returns");const{expression:o,artifact:i,options:s}=r;return{version:Y,expression:Ni(o),options:Fi(s),canonicalForm:Ei(i),issues:wn(i,s,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:i.timeoutShielded,nodeCount:i.nodeCount,maxDepth:i.maxDepth,dependencies:Vi(i.dependencies),own:{nodeCount:i.own.nodeCount,maxDepth:i.own.maxDepth,dependencies:Vi(i.own.dependencies)}}},Mi="[supplied]",Fi=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Li(e,t)])),Li=(e,t)=>{switch(e){case"data":{const e="object"==typeof t&&null!==t?Object.keys(t).length:0;return`[supplied: ${e} top-level key${1===e?"":"s"}]`}case"signal":return Mi;case"http":case"graphQL":return Ri(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):Ni(e));case"cache":return Ri(t,"store",()=>Mi);default:return Ni(t)}},Ri=(e,t,r)=>"object"==typeof e&&null!==e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,a])=>[e,e===t?r(a):Ni(a)])):Ni(e),Vi=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{R as ARRAY,ni as AxiosClient,i as ErrorCodes,fe as EvaluationData,ai as FetchClient,zo as FigTree,P as FigTreeError,V as OBJECT,me as OPERATOR_CATEGORIES,ya as OperatorFailure,Ai as PostgresConnection,Di as SQLiteConnection,C as WILDCARD,F as compareValues,So as coreOperators,X as deepEqual,Zo as defineOperator,ji as httpOperators,zi as inspect,A as isFigTreeError,ga as isOperatorFailure,M as isTruthy,g as parsePath,I as renderText,k as resolvePath,Pi as sqlOperators,Y as version};
|
|
1
|
+
import{O as t,i as a,a as r,b as n,E as i,c as o,d as s,N as d,e as c,R as p,f as m,g as h,h as f,j as v,r as b,k as g,l as P,m as j,p as $,t as D,s as k,v as N,n as O,o as E}from"./chunks/engine.js";export{A as ARRAY,F as FigTree,q as OBJECT,u as compareValues,w as coreOperators,x as deepEqual,y as isOperatorFailure,z as isTruthy}from"./chunks/engine.js";import{f as C,E as L,g as S,R as T,F as Q,h as R,j as J,i as G,D as U,k as V}from"./chunks/shared.js";export{W as WILDCARD,l as isFigTreeError,e as parsePath}from"./chunks/shared.js";const M=/[a-z]Default$/,B=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),I=/*#__PURE__*/new Set(t),H=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),Y=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),K=(e,t)=>{const[a]=e,r=e.length-1,n=r>0?`${a.message} (+ ${r} more issue${1===r?"":"s"})`:a.message;throw new Q({code:L.invalidDefinition,message:n,path:a.path,...void 0!==t?{operator:t}:{},issues:e})};function X(e){if(a(e))return e;const t=[],l=C(e)?e.name:void 0,u="string"==typeof l?l:void 0,y=(e,a,r,n)=>{t.push({severity:"error",code:e,message:a,path:r,...void 0!==u?{operator:u}:{},...void 0!==n?{parameter:n}:{}})};C(e)||(y(L.invalidDefinition,"a definition must be a plain object",[]),K(t));const f=e;"string"!=typeof f.name&&y(L.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof f.description&&""!==f.description||y(L.invalidDefinition,"'description' is required and must be non-empty",["description"]),C(f.parameters)||y(L.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof f.evaluate&&y(L.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),t.length>0&&K(t,u),"string"!=typeof f.category?y(L.invalidDefinition,`'category' is required and must be one of ${[...I].join(", ")}`,["category"]):I.has(f.category)||y(L.invalidDefinition,`'${f.category}' is not a category — expected one of ${[...I].join(", ")}`,["category"]),void 0!==f.alias&&"string"!=typeof f.alias&&y(L.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==f.cache&&!0!==f.cache&&y(L.invalidDefinition,"'cache' must be the literal true",["cache"]),void 0===f.metadata||C(f.metadata)||y(L.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===f.positionalParams||Array.isArray(f.positionalParams)&&!f.positionalParams.some(e=>"string"!=typeof e)||y(L.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==f.timeoutParam&&"string"!=typeof f.timeoutParam&&y(L.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==f.validate&&"function"!=typeof f.validate&&y(L.invalidDefinition,"'validate' must be a function",["validate"]),void 0===f.returns||r(f.returns)||y(L.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const v=(e,t,a)=>{e===i?y(L.invalidDefinition,"the EvaluationData sentinel is legal only as a parameter 'default'",t,a):Array.isArray(e)&&e.forEach((e,r)=>{e===i&&v(e,[...t,r],a)})};for(const[e,t]of Object.entries(f))"parameters"!==e&&"metadata"!==e&&v(t,[e]);const b=(e,t)=>{const a=S(e);a.ok?R.has(e)&&y(L.reservedName,`'${e}' is a reserved name`,t):y(L.invalidName,`'${e}': ${a.reason}`,t)};"string"==typeof f.name&&b(f.name,["name"]),"string"==typeof f.alias&&b(f.alias,["alias"]);const g=f.parameters,w={};for(const[e,t]of Object.entries(g)){const a=["parameters",e],r=S(e);r.ok?T.has(e)&&y(L.reservedName,`'${e}' is a reserved node key and cannot name a parameter`,a,e):y(L.invalidName,`'${e}': ${r.reason}`,a,e),C(t)?w[e]=t:y(L.invalidDefinition,`the declaration for '${e}' must be a plain object`,a,e)}const P={};for(const[e,t]of Object.entries(w)){const a=["parameters",e],l=e=>[...a,e],u=t;for(const[t,a]of Object.entries(u))"default"!==t&&"metadata"!==t&&v(a,l(t),e);let p=!0;void 0===u.type||r(u.type)||(y(L.invalidDefinition,"'type' must be a metadata-vocabulary type",l("type"),e),p=!1),p&&(P[e]=u.type??"any");let m=!1;if(void 0!==u.constraints){const t=n(u.constraints);t.ok?m=!0:y(L.invalidDefinition,`'constraints' is malformed: expected ${t.expected}, got ${t.actual}`,l("constraints"),e)}void 0!==u.required&&"boolean"!=typeof u.required&&y(L.invalidDefinition,"'required' must be a boolean",l("required"),e),void 0!==u.description&&"string"!=typeof u.description&&y(L.invalidDefinition,"'description' must be a string",l("description"),e),void 0===u.metadata||C(u.metadata)||y(L.invalidDefinition,"'metadata' must be a plain object",l("metadata"),e);const h="default"in u;if(h&&!0===u.required&&y(L.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",l("default"),e),h&&u.default!==i){const t=P[e];if(void 0!==t){const a=o(u.default,t);if(a.ok){if(m&&void 0!==u.constraints){const t=s(u.default,u.constraints);t.ok||y(L.typeCheck,`'default' violates the declared constraints: expected ${t.expected}, got ${t.actual}`,l("default"),e)}}else y(L.typeCheck,`'default' does not satisfy the declared type: expected ${a.expected}, got ${a.actual}`,l("default"),e)}}if(void 0===u.evaluation||B.has(u.evaluation)||y(L.invalidDefinition,`'evaluation' must be one of ${[...B].join(", ")}`,l("evaluation"),e),void 0!==u.truthiness&&"boolean"!=typeof u.truthiness&&y(L.invalidDefinition,"'truthiness' must be a boolean",l("truthiness"),e),void 0!==u.over&&"string"!=typeof u.over&&y(L.invalidDefinition,"'over' must be a parameter name",l("over"),e),void 0===u.replacesNullAt||Array.isArray(u.replacesNullAt)&&!u.replacesNullAt.some(e=>"string"!=typeof e)||y(L.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",l("replacesNullAt"),e),void 0!==u.nullPolicy){const t=u.nullPolicy;"function"==typeof t||d.has(t)||y(L.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",l("nullPolicy"),e);const a=P[e];void 0===a||c(a)||y(L.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",l("nullPolicy"),e),!0===u.truthiness&&"propagate"===t&&y(L.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",l("nullPolicy"),e)}if(void 0!==u.elementNullPolicy){d.has(u.elementNullPolicy)||y(L.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",l("elementNullPolicy"),e);const t=P[e];void 0===t||Y(t)||y(L.invalidNullPolicy,"'elementNullPolicy' applies to container parameters only",l("elementNullPolicy"),e)}}if(Array.isArray(f.positionalParams)&&f.positionalParams.every(e=>"string"==typeof e)){const e=new Set,t=f.positionalParams;t.forEach((a,r)=>{const n=a.startsWith(p),i=n?a.slice(p.length):a;n&&r!==t.length-1&&y(L.invalidDefinition,`the rest entry '${a}' must be the last positional entry`,["positionalParams",r]),i in w||y(L.invalidDefinition,`positional entry '${a}' names no declared parameter`,["positionalParams",r]),e.has(i)&&y(L.invalidDefinition,`duplicate positional entry '${a}'`,["positionalParams",r]),e.add(i)})}for(const[e,t]of Object.entries(w)){const a=["parameters",e],r="perElement"===t.evaluation;if(void 0!==t.over&&"string"==typeof t.over)if(r){const r=t.over;if(r in w&&r!==e){const t=P[r];void 0===t||H(t)||y(L.invalidDefinition,`the 'over' target '${r}' must admit an array`,[...a,"over"],e)}else y(L.invalidDefinition,`'over' names no sibling parameter ('${r}')`,[...a,"over"],e)}else y(L.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...a,"over"],e);else r&&y(L.invalidDefinition,"evaluation: 'perElement' requires 'over' to name the iterated sibling",[...a,"evaluation"],e)}for(const[e,t]of Object.entries(w)){if(void 0===t.replacesNullAt)continue;if(!Array.isArray(t.replacesNullAt)||t.replacesNullAt.some(e=>"string"!=typeof e))continue;const a=["parameters",e,"replacesNullAt"];"lazy"!==t.evaluation&&y(L.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",a,e);(t.required??!("default"in t))&&y(L.invalidDefinition,"a 'replacesNullAt' holder must be optional",a,e),"default"in t&&y(L.invalidDefinition,"a 'replacesNullAt' holder may not carry a 'default' — it is presence-sensitive by construction",a,e),t.replacesNullAt.forEach((t,r)=>{t===e?y(L.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...a,r],e):t in w||y(L.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...a,r],e)})}for(const[e,t]of Object.entries(w))M.test(e)&&"lazy"!==t.evaluation&&y(L.invalidDefinition,`'${e}' is named for the '…Default' family, so it must declare evaluation: 'lazy' — add 'replacesNullAt', read it as a LazyValue in the body, or rename it`,["parameters",e,"evaluation"],e);const j=m(w,P,y);if("string"==typeof f.timeoutParam){void 0===w[f.timeoutParam]?y(L.invalidDefinition,`'timeoutParam' names no declared parameter ('${f.timeoutParam}')`,["timeoutParam"]):"integer"!==P[f.timeoutParam]&&y(L.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return t.length>0&&K(t,u),h(f,j)}const Z=e=>new f(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),_=(e,t)=>{const a=t instanceof Error?t.message:String(t),r=t??{},n={driver:e};for(const e of["code","table","column","constraint"])"string"==typeof r[e]&&(n[e]=r[e]);return new f(`${e}: ${a}`,{errorData:n})},ee=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class te{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new f("FetchClient(): this runtime has no global fetch — pass one, new FetchClient(myFetch), or use another client such as new AxiosClient(axios)");this.supplied=e}request=async e=>{const t=this.supplied??globalThis.fetch,a=await t.call(globalThis,e.url,{method:e.method.toUpperCase(),headers:e.headers,...void 0!==e.body?{body:JSON.stringify(e.body)}:{},signal:e.signal}),r=await a.text();if(!a.ok)throw Z({status:a.status,statusText:a.statusText,url:a.url||e.url,payload:ne(r)});return re(r,a.url||e.url,a.status)}}class ae{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new f("AxiosClient(axios): pass the axios import itself — new AxiosClient(axios)")}request=async e=>{try{const t=await this.axios({url:e.url,method:e.method,headers:e.headers,...void 0!==e.body?{data:e.body}:{},signal:e.signal});return""===t.data||void 0===t.data?null:t.data}catch(t){if(this.axios.isAxiosError(t)&&t.response)throw Z({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const re=(e,t,a)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new f(`response was not JSON (${a}): ${t}`,{errorData:{status:a,url:t,response:ee(e)}})}},ne=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return ee(e)}},ie=/^https?:\/\//i,oe=(e,t,a)=>{const r=ie.test(e)?e:se(a,e),n=le(t),i=""===n?r:`${r}${r.includes("?")?"&":"?"}${n}`;try{new URL(i)}catch{throw new f(`'${i}' is not a valid URL`,{code:L.typeCheck})}return i},se=(e,t)=>{if(void 0===e||""===e)throw new f(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:L.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},le=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[a,r]of Object.entries(e))null!=r&&t.append(a,ce(r,`query['${a}']`,"query"));return t.toString()},ue=(...e)=>{const t={};for(const a of e)if(void 0!==a)for(const[e,r]of Object.entries(a))null!=r?t[e]=ce(r,`headers['${e}']`,"header"):delete t[e];return t},de=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),ce=(e,t,a)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return b(e);throw new f(`${t} is ${g(e)} — a ${a} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:L.typeCheck})},pe=e=>({method:e.method,url:e.url,headers:Object.fromEntries(Object.entries(e.headers).sort(([e],[t])=>e<t?-1:e>t?1:0)),...void 0!==e.body?{body:e.body}:{}}),me=e=>Array.isArray(e)?e.length>0:C(e)?Object.keys(e).length>0:null!=e,he=(e,t)=>{if(void 0===t)return e;const a=J(e,v(t));return a.found?void 0===a.value?null:a.value:null},ye=(e,t)=>{if(!C(e))throw new f("a row was not an object");const a=Object.values(e);if(1!==a.length)throw new f(`shape: '${t}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:L.typeCheck});return a[0]},fe={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},ve={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},be=e=>j({name:"http",category:"io",description:"One HTTP request — GET or POST — returning the parsed JSON response",parameters:{url:{type:"string",description:"A full http(s) URL is used verbatim; anything else — including an empty string — joins http.baseEndpoint"},method:{type:{literal:["get","post"]},default:"get",description:"Lowercase; the mutating verbs are deliberately absent — an expression is a read"},query:{type:"object",required:!1,elementNullPolicy:"value",description:"Query-string pairs; a null value omits its pair, a composite one is an error"},body:{type:["string","number","boolean","array","object"],required:!1,description:"The JSON payload; a whole-null body means NO body, while nulls inside one are JSON nulls"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over the http.headers option per key; a null value removes an inherited pair"},returnPath:ve,timeout:fe},positionalParams:["url"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e,method:t,body:a})=>[...$(e,"returnPath"),...Pe(t,a)],evaluate:async({url:t,method:a,query:r,body:n,headers:i,returnPath:o},s)=>{if("get"===a&&void 0!==n)throw new f("a GET carries no body — did you mean method: 'post'?",{code:L.typeCheck});const l={method:a,url:oe(t,r,s.options.http?.baseEndpoint),headers:ue(de(void 0!==n),s.options.http?.headers,i),...void 0!==n?{body:n}:{}},u=await s.cache.memo(pe(l),()=>(De(s,l),e.request({...l,signal:s.signal})));return he(u,o)}}),ge=e=>j({name:"graphQL",category:"io",description:"One GraphQL query — a POST of { query, variables } — returning the data field",parameters:{query:{type:"string",description:"The GraphQL document — the protocol’s own word, as sql.query is"},variables:{type:"object",required:!1,elementNullPolicy:"value",description:"Query variables; a null value is CARRIED as JSON null, a nullable argument being meaningful GraphQL"},url:{type:"string",required:!1,description:"Per-node endpoint override; unset means the graphQL.endpoint option"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over http.headers then graphQL.headers; a null value removes a pair"},returnPath:ve,timeout:fe},positionalParams:["query","variables"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e})=>$(e,"returnPath"),evaluate:async({query:t,variables:a,url:r,headers:n,returnPath:i},o)=>{const s=r??o.options.graphQL?.endpoint;if(void 0===s)throw new f("no endpoint — supply url, or set the graphQL.endpoint option");const l={method:"post",url:oe(s,void 0,o.options.http?.baseEndpoint),headers:ue(de(!0),o.options.http?.headers,o.options.graphQL?.headers,n),body:{query:t,...me(a)?{variables:a}:{}}},u=await o.cache.memo(pe(l),async()=>(De(o,l),(e=>{if(!C(e))throw new f("the GraphQL response was not an object");const t=e.errors;if(Array.isArray(t)&&t.length>0){const e=t[0]?.message;throw new f(`the GraphQL response carried ${t.length} error${1===t.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:t}})}if(!("data"in e))throw new f("the GraphQL response carried neither data nor errors");return e.data??null})(await e.request({...l,signal:o.signal}))));return he(u,i)}}),we=e=>j({name:"sql",category:"io",description:"One SQL query against the registered connection. Expressions are READS — give the connection a read-only role and run mutations host-side",parameters:{query:{type:"string",description:"SQL text with the driver’s own placeholders — FigTree never parses SQL"},values:{type:["array","object"],required:!1,elementNullPolicy:"value",description:"Bind values — positional as an array, named as an object; a null binds SQL NULL"},shape:{type:{literal:["rows","firstRow","column","firstValue"]},default:"rows",description:"rows: every row object; firstRow: the first; column: one column’s values; firstValue: one scalar"},noRowDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The answer when firstRow / firstValue find no row — never for rows / column, never on failure"},timeout:fe},positionalParams:["query","...values"],timeoutParam:"timeout",cache:!0,returns:"any",evaluate:async({query:t,values:a,shape:r,noRowDefault:n},i)=>{const o={text:t,...me(a)?{values:a}:{}};return(async(e,t,a)=>{switch(t){case"rows":return e;case"firstRow":return 0===e.length?a.evaluate():e[0];case"column":return e.map(e=>ye(e,"column"));case"firstValue":return 0===e.length?a.evaluate():ye(e[0],"firstValue")}})(await i.cache.memo(o,()=>(i.trace.note({type:"query",text:o.text}),e.query({...o,signal:i.signal}))),r,n)}}),Pe=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],je=(e=new te)=>[P(be(e)),P(ge(e))],$e=e=>[P(we(e))],De=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class ke{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new f("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new f("postgres takes positional binds ($1, $2, …) — an object of named binds needs a driver that supports them");try{const t=await this.client.query({text:e.text,...void 0!==e.values?{values:e.values}:{}});return t?.rows??[]}catch(e){throw _("postgres",e)}}}class qe{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new f("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw _("sqlite",e)}}}const Ae=e=>xe(e,0,new Set),xe=(e,t,a)=>{if(null===e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e&&Number.isFinite(e)&&!Object.is(e,-0))return e;if("object"!=typeof e)return Ne(e);if(!Array.isArray(e)&&!G(e))return Oe(e);if(a.has(e))return"[circular]";if(t>=U)return"[too deep]";a.add(e);const r=Array.isArray(e)?Array.from(e,e=>xe(e,t+1,a)):Object.fromEntries(Object.entries(e).map(([e,r])=>[e,xe(r,t+1,a)]));return a.delete(e),r},Ne=e=>{switch(typeof e){case"function":return""===e.name?"[function]":`[function ${e.name}]`;case"symbol":return`[${String(e)}]`;case"bigint":return`[bigint ${e}]`;case"number":return Object.is(e,-0)?"[-0]":`[${e}]`;default:return"[undefined]"}},Oe=e=>{const t=Ee(e);try{const a=e.toJSON;if("function"==typeof a){const r=a.call(e);if("string"==typeof r)return`[${t} ${r}]`}}catch{}return`[${t}]`},Ee=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},Ce=e=>{const t=new Map;for(const a of e.holes)void 0!==a.timeoutFallback&&t.set(a.node,a.timeoutFallback);const a=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])),r=e=>{const a=t.get(e);return void 0===a?{}:{timeoutFallback:Ae(a.value)}},n=e=>{const t={order:e.order,kind:e.kind,path:D(e.path)},i="vars"in e&&void 0!==e.vars?{vars:a(e.vars)}:{};switch(e.kind){case"constant":return{...t,kind:e.kind,value:Ae(e.value)};case"reference":return{...t,kind:e.kind,reference:V(e.binding??e.namespace,e.segments),authored:e.raw,...void 0===e.binding?{}:{binding:e.binding}};case"operator":return{...t,kind:e.kind,...i,operator:e.name,params:a(e.params),...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache},...void 0===e.entry.instanceDefaults?{}:{instanceDefaults:Object.keys(e.entry.instanceDefaults)}};case"fragmentCall":return{...t,kind:e.kind,...i,fragment:e.name,resolved:void 0!==e.entry,argumentsMode:e.argumentsMode,...void 0===e.parameters?{}:{parameters:"dynamic"===e.argumentsMode?n(e.parameters):a(e.parameters)},...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache}};case"skeleton":{const a=k(e.skeleton,e.holes,e.holes.map(()=>"<hole>"));return{...t,kind:e.kind,...i,shape:Ae(a),holes:e.holes.map(e=>({at:[...e.at],node:n(e.node)}))}}case"elements":return{...t,kind:e.kind,elements:e.nodes.map(n)};case"entries":return{...t,kind:e.kind,...i,entries:a(e.entries)};case"invalid":return{...t,kind:e.kind,raw:Ae(e.raw)}}};return n(e.root)},Le=(e,t)=>{const a=N(e,t);if(void 0===a)throw new TypeError("inspect() takes a CompiledExpression — the handle fig.compile() returns");const{expression:r,artifact:n,options:i}=a;return{version:O,expression:Ae(r),options:Te(i),canonicalForm:Ce(n),issues:E(n,i,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:n.timeoutShielded,nodeCount:n.nodeCount,maxDepth:n.maxDepth,dependencies:Fe(n.dependencies),own:{nodeCount:n.own.nodeCount,maxDepth:n.own.maxDepth,dependencies:Fe(n.own.dependencies)}}},Se="[supplied]",Te=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Qe(e,t)])),Qe=(e,t)=>{switch(e){case"data":{const e="object"==typeof t&&null!==t?Object.keys(t).length:0;return`[supplied: ${e} top-level key${1===e?"":"s"}]`}case"signal":return Se;case"http":case"graphQL":return Re(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):Ae(e));case"cache":return Re(t,"store",()=>Se);default:return Ae(t)}},Re=(e,t,a)=>"object"==typeof e&&null!==e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,r])=>[e,e===t?a(r):Ae(r)])):Ae(e),Fe=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{ae as AxiosClient,L as ErrorCodes,i as EvaluationData,te as FetchClient,Q as FigTreeError,t as OPERATOR_CATEGORIES,f as OperatorFailure,ke as PostgresConnection,qe as SQLiteConnection,X as defineOperator,je as httpOperators,Le as inspect,b as renderText,J as resolvePath,$e as sqlOperators,O as version};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fig-tree-evaluator",
|
|
3
|
-
"version": "3.0.0-preview.
|
|
3
|
+
"version": "3.0.0-preview.6",
|
|
4
4
|
"description": "Module to evaluate JSON-structured expression trees",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./build/index.js",
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
"./format": {
|
|
23
23
|
"types": "./build/format/index.d.ts",
|
|
24
24
|
"default": "./build/format/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./authoring": {
|
|
27
|
+
"types": "./build/authoring/index.d.ts",
|
|
28
|
+
"default": "./build/authoring/index.js"
|
|
25
29
|
}
|
|
26
30
|
},
|
|
27
31
|
"typesVersions": {
|
|
@@ -34,6 +38,9 @@
|
|
|
34
38
|
],
|
|
35
39
|
"format": [
|
|
36
40
|
"./build/format/index.d.ts"
|
|
41
|
+
],
|
|
42
|
+
"authoring": [
|
|
43
|
+
"./build/authoring/index.d.ts"
|
|
37
44
|
]
|
|
38
45
|
}
|
|
39
46
|
},
|