fig-tree-evaluator 3.0.0-preview.6 → 3.0.0-preview.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/authoring/index.d.ts +20 -3
- package/build/authoring/index.js +1 -1
- package/build/chunks/engine.js +1 -1
- package/build/chunks/shared.js +1 -1
- package/build/format/index.js +1 -1
- package/build/index.d.ts +98 -14
- package/build/index.js +1 -1
- package/build/migrate/index.js +1 -1
- package/package.json +4 -1
package/build/chunks/shared.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e extends Error{code;path;operator;fragment;fragmentPath;errorData;related;cause;issues;trace;constructor(e){super(e.message),this.name="FigTreeError",this.code=e.code,this.path=e.path,void 0!==e.operator&&(this.operator=e.operator),void 0!==e.fragment&&(this.fragment=e.fragment),void 0!==e.fragmentPath&&(this.fragmentPath=e.fragmentPath),void 0!==e.errorData&&(this.errorData=e.errorData),void 0!==e.related&&(this.related=e.related),void 0!==e.cause&&(this.cause=e.cause),void 0!==e.issues&&(this.issues=e.issues),void 0!==e.trace&&(this.trace=e.trace)}prettyPrint(){const e=this.operator?` (operator: ${this.operator})`:"",n=this.path.length>0?` at ${t(this.path)}`:"",r=`${this.code}${e}${n}`,a=this.errorData&&Object.keys(this.errorData).length>0?`\n${JSON.stringify(this.errorData,null,2)}`:"";return`${r}\n${this.message}${a}`}}const n=n=>n instanceof e,t=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:0===n?e:`.${e}`).join(""),r={unknownOperator:"unknown-operator",typeCheck:"type-check",operatorFailure:"operator-failure",timeout:"timeout",requestTimeout:"request-timeout",aborted:"aborted",unknownNodeKey:"unknown-node-key",unresolvedVar:"unresolved-var",unrecognizedIdentifier:"unrecognized-identifier",depthCeiling:"depth-ceiling",nonFiniteResult:"non-finite-result",escapedHandle:"escaped-handle",emptyAggregate:"empty-aggregate",malformedNode:"malformed-node",unknownFragment:"unknown-fragment",positionalArity:"positional-arity",invalidVars:"invalid-vars",invalidReference:"invalid-reference",uselessModifier:"useless-modifier",unreferencedVar:"unreferenced-var",missingRequired:"missing-required",unresolvedParam:"unresolved-param",unresolvedBinding:"unresolved-binding",deadBinding:"dead-binding",invalidAs:"invalid-as",maxDepthExceeded:"max-depth",maxNodesExceeded:"max-nodes",returnsMismatch:"returns-mismatch",fallbackMismatch:"fallback-mismatch",operatorValidate:"operator-validate",missingDataPath:"missing-data-path",shadowedVar:"shadowed-var",varCycle:"var-cycle",bareVars:"bare-vars",fragmentCycle:"fragment-cycle",unboundToken:"unbound-token",unusedSubstitution:"unused-substitution",inertReferenceToken:"inert-reference-token",invalidDefinition:"invalid-definition",invalidName:"invalid-name",reservedName:"reserved-name",invalidNullPolicy:"invalid-null-policy",duplicateOperator:"duplicate-operator",invalidOptions:"invalid-options"},a=()=>{},i=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then,s=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),o=e=>{if("object"!=typeof e||null===e||Array.isArray(e))return!1;const n=Object.getPrototypeOf(e);return n===Object.prototype||null===n},l=(e,n)=>{if(e===n)return 0;const
|
|
1
|
+
class e extends Error{code;path;operator;fragment;fragmentPath;errorData;related;cause;issues;trace;constructor(e){super(e.message),this.name="FigTreeError",this.code=e.code,this.path=e.path,void 0!==e.operator&&(this.operator=e.operator),void 0!==e.fragment&&(this.fragment=e.fragment),void 0!==e.fragmentPath&&(this.fragmentPath=e.fragmentPath),void 0!==e.errorData&&(this.errorData=e.errorData),void 0!==e.related&&(this.related=e.related),void 0!==e.cause&&(this.cause=e.cause),void 0!==e.issues&&(this.issues=e.issues),void 0!==e.trace&&(this.trace=e.trace)}prettyPrint(){const e=this.operator?` (operator: ${this.operator})`:"",n=this.path.length>0?` at ${t(this.path)}`:"",r=`${this.code}${e}${n}`,a=this.errorData&&Object.keys(this.errorData).length>0?`\n${JSON.stringify(this.errorData,null,2)}`:"";return`${r}\n${this.message}${a}`}}const n=n=>n instanceof e,t=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:0===n?e:`.${e}`).join(""),r={unknownOperator:"unknown-operator",typeCheck:"type-check",operatorFailure:"operator-failure",timeout:"timeout",requestTimeout:"request-timeout",aborted:"aborted",unknownNodeKey:"unknown-node-key",unresolvedVar:"unresolved-var",unrecognizedIdentifier:"unrecognized-identifier",depthCeiling:"depth-ceiling",nonFiniteResult:"non-finite-result",escapedHandle:"escaped-handle",emptyAggregate:"empty-aggregate",malformedNode:"malformed-node",unknownFragment:"unknown-fragment",positionalArity:"positional-arity",invalidVars:"invalid-vars",invalidReference:"invalid-reference",uselessModifier:"useless-modifier",unreferencedVar:"unreferenced-var",missingRequired:"missing-required",unresolvedParam:"unresolved-param",unresolvedBinding:"unresolved-binding",deadBinding:"dead-binding",invalidAs:"invalid-as",maxDepthExceeded:"max-depth",maxNodesExceeded:"max-nodes",returnsMismatch:"returns-mismatch",fallbackMismatch:"fallback-mismatch",operatorValidate:"operator-validate",missingDataPath:"missing-data-path",shadowedVar:"shadowed-var",varCycle:"var-cycle",bareVars:"bare-vars",fragmentCycle:"fragment-cycle",unboundToken:"unbound-token",unusedSubstitution:"unused-substitution",inertReferenceToken:"inert-reference-token",invalidDefinition:"invalid-definition",invalidName:"invalid-name",reservedName:"reserved-name",invalidNullPolicy:"invalid-null-policy",duplicateOperator:"duplicate-operator",invalidOptions:"invalid-options"},a=()=>{},i=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then,s=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),o=e=>{if("object"!=typeof e||null===e||Array.isArray(e))return!1;const n=Object.getPrototypeOf(e);return n===Object.prototype||null===n},l=(e,n,t)=>{if(e===n)return 0;const r=e.length,a=n.length;if(Math.abs(r-a)>t)return t+1;let i=new Array(a+1),s=new Array(a+1);for(let e=0;e<=a;e++)i[e]=e;for(let o=1;o<=r;o++){s[0]=o;let r=o;const l=e.charCodeAt(o-1);for(let e=1;e<=a;e++){const t=i[e-1]+(l===n.charCodeAt(e-1)?0:1),a=Math.min(i[e]+1,s[e-1]+1,t);s[e]=a,a<r&&(r=a)}if(r>t)return t+1;const d=i;i=s,s=d}return i[a]},d=(e,n)=>{let t,r=3;for(const a of n){const n=l(e,a,r-1);if(n<r&&(t=a,r=n,0===n))break}return t},u=e=>{let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")},c=e=>{let n;return()=>(void 0===n&&(n=(async()=>e())()),n)},m=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"literal"in e,f=(e,n)=>{const t=p(e),r=p(n);return!(!t.any&&!r.any)||(void 0!==t.literals&&void 0!==r.literals?t.literals.some(e=>r.literals.includes(e)):void 0!==t.literals?t.literals.some(e=>h(e,r.basics)):void 0!==r.literals?r.literals.some(e=>h(e,t.basics)):t.basics.some(e=>r.basics.includes(e)||"integer"===e&&r.basics.includes("number")||"number"===e&&r.basics.includes("integer")))},p=e=>{if(m(e))return{any:!1,basics:[],literals:e.literal};const n="string"==typeof e?[e]:e;return{any:n.includes("any"),basics:n}},h=(e,n)=>"string"==typeof e?n.includes("string"):"boolean"==typeof e?n.includes("boolean"):n.includes("number")||Number.isInteger(e)&&n.includes("integer"),g=/*#__PURE__*/new Set(["operator","fragment","parameters","fallback","noCache","vars","//"]),v=/*#__PURE__*/new Set([...g,"data","params","element","index","d","v","p","e","i","literal"]),y=e=>"string"!=typeof e?{ok:!1,reason:"a name must be a string"}:""===e?{ok:!1,reason:"a name must be non-empty"}:e.startsWith("$")?{ok:!1,reason:"a name may not start with '$'"}:/[.[\]]/.test(e)?{ok:!1,reason:"a name may not contain '.', '[' or ']'"}:{ok:!0},b=Symbol("figtree.path.wildcard"),k=e=>"string"==typeof e||"number"==typeof e||e===b,$={found:!1,value:void 0},x=e=>{const n=[];let t="",r=!1,a=0;const i=()=>{r&&(n.push(t),t="",r=!1)};for(;a<e.length;){const s=e[a];if("."!==s){if("["===s){i();const{segment:t,next:r}=w(e,a);n.push(t),a=r;continue}t+=s,r=!0,a++}else i(),a++}return i(),n},w=(e,n)=>{let t=n+1;if(t>=e.length)throw A(e,'unterminated "["');const r=e[t];if("*"===r){if("]"!==e[t+1])throw A(e,'expected "]" after "[*"');return{segment:b,next:t+2}}if('"'===r||"'"===r){const n=r;t++;let a="";for(;t<e.length;){const r=e[t];if("\\"===r){const n=e[t+1];if(void 0===n)throw A(e,"trailing escape in quoted key");a+=n,t+=2;continue}if(r===n){if("]"!==e[t+1])throw A(e,'expected "]" after quoted key');return{segment:a,next:t+2}}a+=r,t++}throw A(e,"unterminated quoted key")}let a="";for(;t<e.length&&e[t]>="0"&&e[t]<="9";)a+=e[t],t++;if(a.length>0&&"]"===e[t])return{segment:Number(a),next:t+1};throw A(e,'expected a number, "*", or a quoted key inside "[…]"')},A=(e,n)=>new Error(`Invalid path "${e}": ${n}`),j=(e,n)=>P(e,(e=>Array.isArray(e)?e.slice():x(e))(n),0),P=(e,n,t)=>{if(t>=n.length)return{found:!0,value:e};const r=n[t];if(r===b){if(!Array.isArray(e))return $;const r=t+1;if(r>=n.length)return{found:!0,value:e};return{found:!0,value:e.map(e=>{const t=P(e,n,r);return t.found?t.value:null})}}const a=D(e,r);return a.found?P(a.value,n,t+1):$},D=(e,n)=>{if(null===e||"object"!=typeof e)return $;if(Array.isArray(e)){const t="number"==typeof n?n:N(n);return void 0===t||t<0||t>=e.length?$:{found:!0,value:e[t]}}const t=String(n);return Object.prototype.propertyIsEnumerable.call(e,t)?{found:!0,value:e[t]}:$},N=e=>/^\d+$/.test(e)?Number(e):void 0,S=e=>e.map(e=>"string"==typeof e?N(e)??e:e),q={data:"data",d:"data",vars:"vars",v:"vars",params:"params",p:"params",element:"element",e:"element",index:"index",i:"index"},C=e=>{if(!e.startsWith("$"))return null;const n=/^\$([^.[]*)/.exec(e)[1];return{token:n,rest:e.slice(1+n.length)}},O=e=>""===e?[]:x(e.startsWith(".")?e.slice(1):e),W=e=>`${e}Index`,E=(e,n)=>{for(const t of n){if(e===t)return"element";if(e===W(t))return"index"}return null},M=(e,n)=>{const t=C(e);if(null===t)return{kind:"plain"};const{token:a,rest:i}=t,s=q[a];if(void 0===s){const e=void 0===n?.bindings?null:E(a,n.bindings);return null===e?{kind:"unrecognized"}:V(a,i,e)}if(""===i)return"vars"===s?{kind:"invalid",namespace:s,code:r.bareVars,reason:"'$vars' must name a var — there is no whole-scope value"}:{kind:"reference",namespace:s,segments:[],drill:i};if("index"===s)return{kind:"invalid",namespace:s,reason:"'$index' is bare-only — it cannot be drilled"};try{return{kind:"reference",namespace:s,segments:O(i),drill:i}}catch(e){return{kind:"invalid",namespace:s,reason:e.message}}},V=(e,n,t)=>{if("index"===t)return""!==n?{kind:"invalid",namespace:t,reason:"the index binding is bare-only — it cannot be drilled"}:{kind:"reference",namespace:t,segments:[],drill:n,binding:e};try{return{kind:"reference",namespace:t,segments:O(n),drill:n,binding:e}}catch(e){return{kind:"invalid",namespace:t,reason:e.message}}},z=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:e===b?"[*]":I(e,0===n)).join(""),F=/[.[\]"\\]/,I=(e,n)=>""===e||F.test(e)?`["${e.replace(/[\\"]/g,e=>`\\${e}`)}"]`:n?e:`.${e}`,R=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/,T=e=>R.test(e),B=(e,n)=>{const t=z(n);return""===t?`$${e}`:t.startsWith("[")?`$${e}${t}`:`$${e}.${t}`},Z=e=>B("data",e),_=/*#__PURE__*/new Set(["fallback","noCache","vars","//"]),G=500,H={kind:"operator"},J={kind:"fragment"},K={kind:"plain"},L=e=>({kind:"malformed",message:e}),Q=(e,n)=>{const t="operator"in e,r="fragment"in e,a=[];for(const t in e)t.startsWith("$")&&n(t.slice(1))&&a.push(t);return t&&r?L("'operator' and 'fragment' may not share a node"):(t||r)&&a.length>0?L(`a canonical '${t?"operator":"fragment"}' key may not sit beside the shorthand key '${a[0]}'`):t?H:r?J:a.length>=2?L(`one node, one invocation: found ${a.map(e=>`'${e}'`).join(" and ")}`):1===a.length?{kind:"shorthand",key:a[0]}:K},U=(e,n)=>{if(!o(e))return!1;if("operator"in e||"fragment"in e)return!0;for(const t in e)if(t.startsWith("$")&&n(t.slice(1)))return!0;return!1},X=(e,n)=>{const t=e.positionalParams;if(void 0===t)return null;const r=e.restParam,a=null===r?t.length:t.length-1;return n>a&&null===r?null:{bound:Math.min(n,a),restAt:null!==r&&n>=a?a:null}},Y=e=>{const n=e.positionalParams?.[0];return void 0===n?null:n.startsWith("...")?e.restParam:n},ee=["path","default"];export{Z as A,u as B,G as D,r as E,e as F,ee as G,g as R,_ as S,b as W,s as a,n as b,Q as c,o as d,U as e,M as f,C as g,z as h,m as i,x as j,y as k,v as l,B as m,T as n,S as o,X as p,d as q,j as r,Y as s,f as t,E as u,k as v,W as w,a as x,c as y,i as z};
|
package/build/format/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,E as r,p as n,S as a,i as s,a as o,R as i,s as l,r as u,b as f,G as c,d as p,W as m,e as d,F as h,D as k}from"../chunks/shared.js";export{t as typesIntersect}from"../chunks/shared.js";const g=e=>{const r=new Map;for(const{name:t,alias:n,positionalParams:a,restParam:s}of e.getOperators()){const e={name:t,alias:n,positionalParams:a,restParam:s};r.set(t,e),void 0!==n&&r.set(n,e)}const t=new Set(e.getFragments().map(({name:e})=>e));return{operators:r,fragments:t,recognizes:e=>"literal"===e||r.has(e)||t.has(e)}},v=(e,r)=>{const t=n(e,r.length);if(null===t)return null;const a=e.positionalParams,s=[];for(let e=0;e<t.bound;e++)s.push([a[e],r[e]]);return null!==t.restAt&&s.push([e.restParam,0===t.restAt?r:r.slice(t.restAt)]),s},y=/*#__PURE__*/new Set(["fallback","noCache","vars"]),$="'noCache' takes only the literal true — it is settled before the subtree runs",w=(e,t,n)=>{const a=e.operator;if("string"!=typeof a)return n(r.malformedNode,"the 'operator' value must be a literal string");if("literal"===a)return P(e,n);const s=t.operators.get(a);if(void 0===s)return n(r.unknownOperator,`'${a}' names no registered operator`);const o=[],i=[];for(const t in e){const a=e[t];if(void 0!==a)if("operator"===t)o.push({kind:"invocation"});else{if("noCache"===t&&!0!==a)return n(r.malformedNode,$);if("//"===t||y.has(t))o.push({kind:"keep",key:t,value:a});else{if("parameters"===t)return n(r.malformedNode,"'parameters' is reserved and unused on operator nodes");o.push({kind:"param",name:t,value:a}),i.push([t,a])}}}return{kind:"operator",operator:s,spelling:a,slots:o,params:i,fromPayload:!1}},P=(e,t)=>{if(!("value"in e))return t(r.malformedNode,"'literal' requires its content in 'value'");const n=[];for(const a in e){const s=e[a];if("operator"===a)n.push({kind:"invocation"});else if("value"===a)n.push({kind:"param",name:"value",value:s});else{if(void 0===s)continue;if("//"!==a&&!y.has(a))return t(r.unknownNodeKey,`'${a}' is not a key of 'literal' — content goes in 'value'`);n.push({kind:"keep",key:a,value:s})}}return{kind:"literal",content:e.value,slots:n,fromPayload:!1}},A=(e,t,n)=>{const a=e.fragment;if("string"!=typeof a)return n(r.malformedNode,"the 'fragment' value must be a literal string");if(!t.fragments.has(a))return n(r.unknownFragment,`'${a}' names no registered fragment`);const s=[];for(const a in e){const o=e[a];if(void 0!==o)if("fragment"===a)s.push({kind:"invocation"});else if("parameters"===a)N(o,t,n),s.push({kind:"param",name:a,value:o});else{if("noCache"===a&&!0!==o)return n(r.malformedNode,$);if("//"!==a&&!y.has(a))return n(r.unknownNodeKey,`'${a}' is not a key of a fragment call — arguments live only in 'parameters'`);s.push({kind:"keep",key:a,value:o})}}return{kind:"fragment",name:a,slots:s,parameters:e.parameters,fromPayload:!1}},N=(e,t,n)=>{s(e)||o(e,t.recognizes)||"string"==typeof e&&"reference"===u(e).kind||n(r.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one")},b=(e,t,n,o)=>{const i=t.slice(1),l="literal"===i,u=!l&&n.fragments.has(i),f=[];for(const n in e){const s=e[n];if(n!==t){if(!a.has(n))return o(r.malformedNode,`'${n}' may not sit beside the shorthand key '${t}' — reserved modifiers only`);if("noCache"===n&&!0!==s&&!l)return o(r.malformedNode,$);void 0!==s&&f.push({kind:"keep",key:n,value:s})}else f.push({kind:"invocation"})}const c=e[t];if(l)return{kind:"literal",content:c,slots:f,fromPayload:!0};if(u)return s(c)?{kind:"fragment",name:i,slots:f,parameters:c,fromPayload:!0}:o(r.malformedNode,`fragments have no single-value or positional form — '${t}' takes a named-arguments object`);const p=n.operators.get(i);return{kind:"operator",operator:p,spelling:i,slots:f,params:j(p,c,n,o),fromPayload:!0}},j=(e,t,n,a)=>{const u=()=>a(r.positionalArity,`'${e.name}' takes no positional arguments — use the named form`);if(Array.isArray(t)){const n=v(e,t);if(null!==n)return n;if(void 0===e.positionalParams)return u();const s=e.positionalParams;return a(r.positionalArity,`'${e.name}' takes at most ${s.length} positional argument${1===s.length?"":"s"} (${s.join(", ")}), got ${t.length}`)}if(s(t)&&!o(t,n.recognizes)){const n=[];for(const s in t){const o=t[s];if(void 0!==o){if("//"!==s&&i.has(s))return a(r.unknownNodeKey,`'${s}' is not a parameter of '${e.name}'`);n.push([s,o])}}return n}const f=l(e);return null===f?u():[[f,t]]},z={positionalParams:c,restParam:null},C=/*#__PURE__*/new Set(["path","from","default"]),W={data:"d",vars:"v",params:"p",element:"e",index:"i"},x=(e,r,t)=>"canonical"===t?r:"alias"===t?W[r]:e,M=(e,r)=>{if("preserve"===r)return e;const t=u(e);if("reference"!==t.kind)return e;const{token:n,rest:a}=f(e);return`$${x(n,t.namespace,r)}${a}`},S=e=>e.startsWith(".")?e.slice(1):e,F=(e,r)=>{if("string"!=typeof e)return null;const t=u(e);if("reference"!==t.kind)return null;const{namespace:n}=t,{token:a,rest:s}=f(e),o=`$${x(a,n,r)}`;switch(n){case"data":return{operator:"get",path:S(s)};case"element":return{operator:"get",path:S(s),from:o};case"vars":case"params":{if(0===t.segments.length)return{operator:"get",path:"",from:o};const e=(e=>{if(e.startsWith(".")){let r=1;for(;r<e.length&&"."!==e[r]&&"["!==e[r];)r++;return r>1?r:null}const r=e[1];if("["!==e[0]||'"'!==r&&"'"!==r)return null;for(let t=2;t<e.length;t++)if("\\"===e[t])t++;else if(e[t]===r)return"]"===e[t+1]?t+2:null;return null})(s);return null===e?null:{operator:"get",path:S(s.slice(e)),from:`${o}${s.slice(0,e)}`}}default:return null}},K=(e,r)=>{if(e.has("default"))return null;const t=(e=>{if("string"==typeof e){if(e.startsWith("$"))return null;try{return d(e)}catch{return null}}if(!Array.isArray(e))return null;for(const r of e)if(!("string"==typeof r&&!r.startsWith("$")||"number"==typeof r&&Number.isInteger(r)&&r>=0))return null;return e})(e.get("path"));if(null===t)return null;const n=p(t);let a;const s=e.get("from");if(void 0===s)a="canonical"===r?"$data":"$d";else{if("string"!=typeof s)return null;const e=u(s);if("reference"!==e.kind||"index"===e.namespace)return null;if(""!==n&&e.segments.includes(m))return null;a=M(s,r).replace(/\.$/,"")}return""===n?a:n.startsWith("[")?`${a}${n}`:`${a}.${n}`},O=e=>{const r=[];for(let t=e;null!==t;t=t.parent)r.push(t.key);return r.reverse()};class E{lookup;writer;path=null;depth=0;constructor(e,r){this.lookup=e,this.writer=r}fail=(e,r)=>{throw new h({code:e,message:r,path:O(this.path)})};child(e,r){return this.within(r,()=>this.value(e))}within(e,r){const{path:t,depth:n}=this;this.path={parent:t,key:e},this.depth=n+1;const a=r();return this.path=t,this.depth=n,a}value(t){if(this.depth>k&&this.fail(r.depthCeiling,`the expression nests deeper than the engine's ceiling of ${k} levels`),"string"==typeof t)return this.writer.string(t);if(Array.isArray(t))return t.map((e,r)=>this.child(e,r));if(!s(t))return t;const n=((t,n,a)=>{const s=e(t,n.recognizes);switch(s.kind){case"malformed":return a(r.malformedNode,s.message);case"plain":return s;case"operator":return w(t,n,a);case"fragment":return A(t,n,a);case"shorthand":return b(t,s.key,n,a)}})(t,this.lookup,this.fail);switch(n.kind){case"plain":return this.entries(t,!0);case"operator":return this.writer.operator(n,this);case"fragment":return this.writer.fragment(n,this);case"literal":return this.writer.literal(n,this)}}keep({key:e,value:r}){return"fallback"===e?this.child(r,e):"vars"===e?this.vars(r):r}parameters(e){return!s(e)||o(e,this.lookup.recognizes)?this.child(e,"parameters"):this.within("parameters",()=>this.entries(e,!1))}entries(e,r){const t={};for(const n in e){const a=e[n];t[n]="//"===n?a:r&&"vars"===n?this.vars(a):this.child(a,n)}return t}vars(e){return s(e)?this.within("vars",()=>this.entries(e,!1)):e}}const G=(e,r)=>"canonical"===r?e.operator.name:"alias"===r?e.operator.alias??e.operator.name:e.spelling,I=e=>Array.isArray(e)?e:[e],R=(e,r)=>[...I(e),...I(r)],q=e=>e.params.find(([e])=>"//"===e)?.[1],D=e=>e.slots.some(e=>"keep"===e.kind&&"//"===e.key),B={kind:"named"},H=(e,r)=>!(Array.isArray(e)||s(e)&&!o(e,r.recognizes)),J=(e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n="named"===e.arguments,a=e.getAsReference??!0;return{operator:(e,s)=>{const o=e.params.map(([e,r])=>[e,"//"===e?r:s.child(r,e)]),i=o.filter(([e])=>"//"!==e);if(a&&"get"===e.operator.name){const r=e.slots.some(e=>"keep"===e.kind&&"//"!==e.key)?null:K(new Map(i),t);if(null!==r)return r}const l=n?B:((e,r,t)=>{const n=e.positionalParams;if(void 0===n||0===r.length)return B;const a=e.restParam,s=null===a?n:n.slice(0,-1),o=new Map(r);for(const e of o.keys())if(e!==a&&!s.includes(e))return B;let i=0;for(;i<s.length&&o.has(s[i]);)i++;for(let e=i;e<s.length;e++)if(o.has(s[e]))return B;const l=null!==a&&o.has(a);if(null!==a&&l!==(i===s.length))return B;const u=s.slice(0,i).map(e=>o.get(e));if(l){const e=o.get(a);return Array.isArray(e)?{kind:"array",value:[...u,...e]}:0===s.length&&H(e,t)?{kind:"single",value:e}:B}return 1===i&&H(u[0],t)?{kind:"single",value:u[0]}:{kind:"array",value:u}})(e.operator,i,s.lookup),u="named"===l.kind?void 0:q(e),f=void 0!==u&&D(e),c={};for(const t of e.slots)"invocation"===t.kind?(void 0===u||f||(c["//"]=u),c[`$${G(e,r)}`]="named"===l.kind?Object.fromEntries(o):l.value):"keep"===t.kind&&(c[t.key]="//"===t.key&&f?R(t.value,u):s.keep(t));return c},fragment:(e,r)=>{const t=void 0===e.parameters?{}:r.parameters(e.parameters),n="string"==typeof t,a={};for(const s of e.slots)"invocation"===s.kind?n?(a.fragment=e.name,e.fromPayload&&(a.parameters=t)):a[`$${e.name}`]=t:"param"===s.kind?n&&(a.parameters=t):a[s.key]=r.keep(s);return a},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?t.$literal=e.content:"keep"===n.kind&&(t[n.key]=r.keep(n));return t},string:e=>M(e,t)}},L=(e,r,t)=>new E(g(r),((e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n=e.referencesAsGet??!1;return{operator:(e,t)=>{const n={},a=e.fromPayload?q(e):void 0,s=void 0!==a&&D(e);for(const o of e.slots)if("invocation"===o.kind){if(void 0===a||s||(n["//"]=a),n.operator=G(e,r),e.fromPayload)for(const[r,a]of e.params)"//"!==r&&(n[r]=t.child(a,r))}else"param"===o.kind?n[o.name]=t.child(o.value,o.name):"//"===o.key&&s?n["//"]=R(o.value,a):n[o.key]=t.keep(o);return n},fragment:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.fragment=e.name,e.fromPayload&&(t.parameters=r.parameters(e.parameters))):"param"===n.kind?t.parameters=r.parameters(n.value):t[n.key]=r.keep(n);return t},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.operator="literal",e.fromPayload&&(t.value=e.content)):"param"===n.kind?t.value=e.content:t[n.key]=r.keep(n);return t},string:e=>{if(n){const r=F(e,t);if(null!==r)return r}return M(e,t)}}})(t)).value(e),Q=(e,r,t)=>new E(g(r),J(t)).value(e),T=(e,r)=>F(e,r?.referenceNames??"preserve"),U=(e,r)=>{const t=(e=>{if(!s(e))return null;const r=new Map;if("operator"in e){if("get"!==e.operator)return null;for(const t in e){const n=e[t];if("operator"!==t&&"//"!==t&&void 0!==n){if(!C.has(t))return null;r.set(t,n)}}return r}for(const r in e)if("$get"!==r&&"//"!==r)return null;if(!("$get"in e))return null;const t=e.$get;if(Array.isArray(t)){const e=v(z,t);if(null===e)return null;for(const[t,n]of e)r.set(t,n);return r}if(s(t)){for(const e in t){const n=t[e];if("//"!==e&&void 0!==n){if(!C.has(e))return null;r.set(e,n)}}return r}return r.set(l(z),t),r})(e);return null===t?null:K(t,r?.referenceNames??"preserve")};export{e as classifyObject,n as positionalLayout,u as recognizeReference,l as singlePositionalTarget,L as toCanonical,T as toGet,U as toReference,Q as toShorthand};
|
|
1
|
+
import{c as e,E as r,p as n,S as a,d as s,e as o,R as i,s as l,f as u,g as f,G as c,h as p,W as m,j as d,F as h,D as k}from"../chunks/shared.js";export{t as typesIntersect}from"../chunks/shared.js";const g=e=>{const r=new Map;for(const{name:t,alias:n,positionalParams:a,restParam:s}of e.getOperators()){const e={name:t,alias:n,positionalParams:a,restParam:s};r.set(t,e),void 0!==n&&r.set(n,e)}const t=new Set(e.getFragments().map(({name:e})=>e));return{operators:r,fragments:t,recognizes:e=>"literal"===e||r.has(e)||t.has(e)}},v=(e,r)=>{const t=n(e,r.length);if(null===t)return null;const a=e.positionalParams,s=[];for(let e=0;e<t.bound;e++)s.push([a[e],r[e]]);return null!==t.restAt&&s.push([e.restParam,0===t.restAt?r:r.slice(t.restAt)]),s},y=/*#__PURE__*/new Set(["fallback","noCache","vars"]),$="'noCache' takes only the literal true — it is settled before the subtree runs",w=(e,t,n)=>{const a=e.operator;if("string"!=typeof a)return n(r.malformedNode,"the 'operator' value must be a literal string");if("literal"===a)return P(e,n);const s=t.operators.get(a);if(void 0===s)return n(r.unknownOperator,`'${a}' names no registered operator`);const o=[],i=[];for(const t in e){const a=e[t];if(void 0!==a)if("operator"===t)o.push({kind:"invocation"});else{if("noCache"===t&&!0!==a)return n(r.malformedNode,$);if("//"===t||y.has(t))o.push({kind:"keep",key:t,value:a});else{if("parameters"===t)return n(r.malformedNode,"'parameters' is reserved and unused on operator nodes");o.push({kind:"param",name:t,value:a}),i.push([t,a])}}}return{kind:"operator",operator:s,spelling:a,slots:o,params:i,fromPayload:!1}},P=(e,t)=>{if(!("value"in e))return t(r.malformedNode,"'literal' requires its content in 'value'");const n=[];for(const a in e){const s=e[a];if("operator"===a)n.push({kind:"invocation"});else if("value"===a)n.push({kind:"param",name:"value",value:s});else{if(void 0===s)continue;if("//"!==a&&!y.has(a))return t(r.unknownNodeKey,`'${a}' is not a key of 'literal' — content goes in 'value'`);n.push({kind:"keep",key:a,value:s})}}return{kind:"literal",content:e.value,slots:n,fromPayload:!1}},A=(e,t,n)=>{const a=e.fragment;if("string"!=typeof a)return n(r.malformedNode,"the 'fragment' value must be a literal string");if(!t.fragments.has(a))return n(r.unknownFragment,`'${a}' names no registered fragment`);const s=[];for(const a in e){const o=e[a];if(void 0!==o)if("fragment"===a)s.push({kind:"invocation"});else if("parameters"===a)N(o,t,n),s.push({kind:"param",name:a,value:o});else{if("noCache"===a&&!0!==o)return n(r.malformedNode,$);if("//"!==a&&!y.has(a))return n(r.unknownNodeKey,`'${a}' is not a key of a fragment call — arguments live only in 'parameters'`);s.push({kind:"keep",key:a,value:o})}}return{kind:"fragment",name:a,slots:s,parameters:e.parameters,fromPayload:!1}},N=(e,t,n)=>{s(e)||o(e,t.recognizes)||"string"==typeof e&&"reference"===u(e).kind||n(r.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one")},b=(e,t,n,o)=>{const i=t.slice(1),l="literal"===i,u=!l&&n.fragments.has(i),f=[];for(const n in e){const s=e[n];if(n!==t){if(!a.has(n))return o(r.malformedNode,`'${n}' may not sit beside the shorthand key '${t}' — reserved modifiers only`);if("noCache"===n&&!0!==s&&!l)return o(r.malformedNode,$);void 0!==s&&f.push({kind:"keep",key:n,value:s})}else f.push({kind:"invocation"})}const c=e[t];if(l)return{kind:"literal",content:c,slots:f,fromPayload:!0};if(u)return s(c)?{kind:"fragment",name:i,slots:f,parameters:c,fromPayload:!0}:o(r.malformedNode,`fragments have no single-value or positional form — '${t}' takes a named-arguments object`);const p=n.operators.get(i);return{kind:"operator",operator:p,spelling:i,slots:f,params:j(p,c,n,o),fromPayload:!0}},j=(e,t,n,a)=>{const u=()=>a(r.positionalArity,`'${e.name}' takes no positional arguments — use the named form`);if(Array.isArray(t)){const n=v(e,t);if(null!==n)return n;if(void 0===e.positionalParams)return u();const s=e.positionalParams;return a(r.positionalArity,`'${e.name}' takes at most ${s.length} positional argument${1===s.length?"":"s"} (${s.join(", ")}), got ${t.length}`)}if(s(t)&&!o(t,n.recognizes)){const n=[];for(const s in t){const o=t[s];if(void 0!==o){if("//"!==s&&i.has(s))return a(r.unknownNodeKey,`'${s}' is not a parameter of '${e.name}'`);n.push([s,o])}}return n}const f=l(e);return null===f?u():[[f,t]]},z={positionalParams:c,restParam:null},C=/*#__PURE__*/new Set(["path","from","default"]),W={data:"d",vars:"v",params:"p",element:"e",index:"i"},x=(e,r,t)=>"canonical"===t?r:"alias"===t?W[r]:e,M=(e,r)=>{if("preserve"===r)return e;const t=u(e);if("reference"!==t.kind)return e;const{token:n,rest:a}=f(e);return`$${x(n,t.namespace,r)}${a}`},S=e=>e.startsWith(".")?e.slice(1):e,F=(e,r)=>{if("string"!=typeof e)return null;const t=u(e);if("reference"!==t.kind)return null;const{namespace:n}=t,{token:a,rest:s}=f(e),o=`$${x(a,n,r)}`;switch(n){case"data":return{operator:"get",path:S(s)};case"element":return{operator:"get",path:S(s),from:o};case"vars":case"params":{if(0===t.segments.length)return{operator:"get",path:"",from:o};const e=(e=>{if(e.startsWith(".")){let r=1;for(;r<e.length&&"."!==e[r]&&"["!==e[r];)r++;return r>1?r:null}const r=e[1];if("["!==e[0]||'"'!==r&&"'"!==r)return null;for(let t=2;t<e.length;t++)if("\\"===e[t])t++;else if(e[t]===r)return"]"===e[t+1]?t+2:null;return null})(s);return null===e?null:{operator:"get",path:S(s.slice(e)),from:`${o}${s.slice(0,e)}`}}default:return null}},K=(e,r)=>{if(e.has("default"))return null;const t=(e=>{if("string"==typeof e){if(e.startsWith("$"))return null;try{return d(e)}catch{return null}}if(!Array.isArray(e))return null;for(const r of e)if(!("string"==typeof r&&!r.startsWith("$")||"number"==typeof r&&Number.isInteger(r)&&r>=0))return null;return e})(e.get("path"));if(null===t)return null;const n=p(t);let a;const s=e.get("from");if(void 0===s)a="canonical"===r?"$data":"$d";else{if("string"!=typeof s)return null;const e=u(s);if("reference"!==e.kind||"index"===e.namespace)return null;if(""!==n&&e.segments.includes(m))return null;a=M(s,r).replace(/\.$/,"")}return""===n?a:n.startsWith("[")?`${a}${n}`:`${a}.${n}`},O=e=>{const r=[];for(let t=e;null!==t;t=t.parent)r.push(t.key);return r.reverse()};class E{lookup;writer;path=null;depth=0;constructor(e,r){this.lookup=e,this.writer=r}fail=(e,r)=>{throw new h({code:e,message:r,path:O(this.path)})};child(e,r){return this.within(r,()=>this.value(e))}within(e,r){const{path:t,depth:n}=this;this.path={parent:t,key:e},this.depth=n+1;const a=r();return this.path=t,this.depth=n,a}value(t){if(this.depth>k&&this.fail(r.depthCeiling,`the expression nests deeper than the engine's ceiling of ${k} levels`),"string"==typeof t)return this.writer.string(t);if(Array.isArray(t))return t.map((e,r)=>this.child(e,r));if(!s(t))return t;const n=((t,n,a)=>{const s=e(t,n.recognizes);switch(s.kind){case"malformed":return a(r.malformedNode,s.message);case"plain":return s;case"operator":return w(t,n,a);case"fragment":return A(t,n,a);case"shorthand":return b(t,s.key,n,a)}})(t,this.lookup,this.fail);switch(n.kind){case"plain":return this.entries(t,!0);case"operator":return this.writer.operator(n,this);case"fragment":return this.writer.fragment(n,this);case"literal":return this.writer.literal(n,this)}}keep({key:e,value:r}){return"fallback"===e?this.child(r,e):"vars"===e?this.vars(r):r}parameters(e){return!s(e)||o(e,this.lookup.recognizes)?this.child(e,"parameters"):this.within("parameters",()=>this.entries(e,!1))}entries(e,r){const t={};for(const n in e){const a=e[n];t[n]="//"===n?a:r&&"vars"===n?this.vars(a):this.child(a,n)}return t}vars(e){return s(e)?this.within("vars",()=>this.entries(e,!1)):e}}const G=(e,r)=>"canonical"===r?e.operator.name:"alias"===r?e.operator.alias??e.operator.name:e.spelling,I=e=>Array.isArray(e)?e:[e],R=(e,r)=>[...I(e),...I(r)],q=e=>e.params.find(([e])=>"//"===e)?.[1],D=e=>e.slots.some(e=>"keep"===e.kind&&"//"===e.key),B={kind:"named"},H=(e,r)=>!(Array.isArray(e)||s(e)&&!o(e,r.recognizes)),J=(e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n="named"===e.arguments,a=e.getAsReference??!0;return{operator:(e,s)=>{const o=e.params.map(([e,r])=>[e,"//"===e?r:s.child(r,e)]),i=o.filter(([e])=>"//"!==e);if(a&&"get"===e.operator.name){const r=e.slots.some(e=>"keep"===e.kind)||e.params.some(([e])=>"//"===e)?null:K(new Map(i),t);if(null!==r)return r}const l=n?B:((e,r,t)=>{const n=e.positionalParams;if(void 0===n||0===r.length)return B;const a=e.restParam,s=null===a?n:n.slice(0,-1),o=new Map(r);for(const e of o.keys())if(e!==a&&!s.includes(e))return B;let i=0;for(;i<s.length&&o.has(s[i]);)i++;for(let e=i;e<s.length;e++)if(o.has(s[e]))return B;const l=null!==a&&o.has(a);if(null!==a&&l!==(i===s.length))return B;const u=s.slice(0,i).map(e=>o.get(e));if(l){const e=o.get(a);return Array.isArray(e)?{kind:"array",value:[...u,...e]}:0===s.length&&H(e,t)?{kind:"single",value:e}:B}return 1===i&&H(u[0],t)?{kind:"single",value:u[0]}:{kind:"array",value:u}})(e.operator,i,s.lookup),u="named"===l.kind?void 0:q(e),f=void 0!==u&&D(e),c={};for(const t of e.slots)"invocation"===t.kind?(void 0===u||f||(c["//"]=u),c[`$${G(e,r)}`]="named"===l.kind?Object.fromEntries(o):l.value):"keep"===t.kind&&(c[t.key]="//"===t.key&&f?R(t.value,u):s.keep(t));return c},fragment:(e,r)=>{const t=void 0===e.parameters?{}:r.parameters(e.parameters),n="string"==typeof t,a={};for(const s of e.slots)"invocation"===s.kind?n?(a.fragment=e.name,e.fromPayload&&(a.parameters=t)):a[`$${e.name}`]=t:"param"===s.kind?n&&(a.parameters=t):a[s.key]=r.keep(s);return a},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?t.$literal=e.content:"keep"===n.kind&&(t[n.key]=r.keep(n));return t},string:e=>M(e,t)}},L=(e,r,t)=>new E(g(r),((e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n=e.referencesAsGet??!1;return{operator:(e,t)=>{const n={},a=e.fromPayload?q(e):void 0,s=void 0!==a&&D(e);for(const o of e.slots)if("invocation"===o.kind){if(void 0===a||s||(n["//"]=a),n.operator=G(e,r),e.fromPayload)for(const[r,a]of e.params)"//"!==r&&(n[r]=t.child(a,r))}else"param"===o.kind?n[o.name]=t.child(o.value,o.name):"//"===o.key&&s?n["//"]=R(o.value,a):n[o.key]=t.keep(o);return n},fragment:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.fragment=e.name,e.fromPayload&&(t.parameters=r.parameters(e.parameters))):"param"===n.kind?t.parameters=r.parameters(n.value):t[n.key]=r.keep(n);return t},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.operator="literal",e.fromPayload&&(t.value=e.content)):"param"===n.kind?t.value=e.content:t[n.key]=r.keep(n);return t},string:e=>{if(n){const r=F(e,t);if(null!==r)return r}return M(e,t)}}})(t)).value(e),Q=(e,r,t)=>new E(g(r),J(t)).value(e),T=(e,r)=>F(e,r?.referenceNames??"preserve"),U=(e,r)=>{const t=(e=>{if(!s(e))return null;const r=new Map;if("operator"in e){if("get"!==e.operator)return null;for(const t in e){const n=e[t];if("operator"!==t&&"//"!==t&&void 0!==n){if(!C.has(t))return null;r.set(t,n)}}return r}for(const r in e)if("$get"!==r&&"//"!==r)return null;if(!("$get"in e))return null;const t=e.$get;if(Array.isArray(t)){const e=v(z,t);if(null===e)return null;for(const[t,n]of e)r.set(t,n);return r}if(s(t)){for(const e in t){const n=t[e];if("//"!==e&&void 0!==n){if(!C.has(e))return null;r.set(e,n)}}return r}return r.set(l(z),t),r})(e);return null===t?null:K(t,r?.referenceNames??"preserve")};export{e as classifyObject,n as positionalLayout,u as recognizeReference,l as singlePositionalTarget,L as toCanonical,T as toGet,U as toReference,Q as toShorthand};
|
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.8";
|
|
2
2
|
|
|
3
3
|
interface HttpRequest {
|
|
4
4
|
url: string;
|
|
@@ -234,6 +234,95 @@ declare const validateHelpers: Readonly<{
|
|
|
234
234
|
}>;
|
|
235
235
|
type ValidateHelpers = typeof validateHelpers;
|
|
236
236
|
|
|
237
|
+
interface FallbackCoverage {
|
|
238
|
+
uncovered: CoverageFinding[];
|
|
239
|
+
covered: CoveredFinding[];
|
|
240
|
+
}
|
|
241
|
+
interface CoverageFinding {
|
|
242
|
+
path: (string | number)[];
|
|
243
|
+
code: FigTreeErrorCode;
|
|
244
|
+
message: string;
|
|
245
|
+
certainty: 'may' | 'always';
|
|
246
|
+
operator?: string;
|
|
247
|
+
parameter?: string;
|
|
248
|
+
fragment?: string;
|
|
249
|
+
fragmentPath?: (string | number)[];
|
|
250
|
+
}
|
|
251
|
+
interface CoveredFinding extends CoverageFinding {
|
|
252
|
+
coveredBy: (string | number)[];
|
|
253
|
+
coveredByFragmentPath?: (string | number)[];
|
|
254
|
+
}
|
|
255
|
+
interface FallbackCoverageOptions {
|
|
256
|
+
strictNumbers?: boolean;
|
|
257
|
+
}
|
|
258
|
+
interface OperatorAnalysis {
|
|
259
|
+
failures?: FailureRule[];
|
|
260
|
+
external?: true;
|
|
261
|
+
output?: DeclaredOutput;
|
|
262
|
+
}
|
|
263
|
+
interface FailureRule {
|
|
264
|
+
code: FigTreeErrorCode;
|
|
265
|
+
parameter?: string;
|
|
266
|
+
when?: Record<string, FailureTest>;
|
|
267
|
+
options?: Record<string, unknown>;
|
|
268
|
+
may?: true;
|
|
269
|
+
overflow?: true;
|
|
270
|
+
}
|
|
271
|
+
type FailureTest = string | number | boolean | null | {
|
|
272
|
+
type: ExpectedType;
|
|
273
|
+
} | {
|
|
274
|
+
below: number;
|
|
275
|
+
} | {
|
|
276
|
+
empty: true;
|
|
277
|
+
} | {
|
|
278
|
+
supplied: boolean;
|
|
279
|
+
} | {
|
|
280
|
+
invalid: true;
|
|
281
|
+
} | {
|
|
282
|
+
some: FailureTest;
|
|
283
|
+
} | {
|
|
284
|
+
not: FailureTest;
|
|
285
|
+
};
|
|
286
|
+
type DeclaredOutput = ExpectedType | {
|
|
287
|
+
type: 'number' | 'integer';
|
|
288
|
+
min?: number;
|
|
289
|
+
max?: number;
|
|
290
|
+
} | {
|
|
291
|
+
type: 'string' | 'array';
|
|
292
|
+
minLength?: number;
|
|
293
|
+
} | {
|
|
294
|
+
param: string;
|
|
295
|
+
} | {
|
|
296
|
+
elementOf: string;
|
|
297
|
+
} | {
|
|
298
|
+
kindOf: string;
|
|
299
|
+
} | {
|
|
300
|
+
arrayOf: DeclaredOutput;
|
|
301
|
+
minLength?: number;
|
|
302
|
+
} | {
|
|
303
|
+
oneOf: DeclaredOutput[];
|
|
304
|
+
} | {
|
|
305
|
+
typeNamedBy: string;
|
|
306
|
+
} | {
|
|
307
|
+
byParam: string;
|
|
308
|
+
cases: Record<string, DeclaredOutput>;
|
|
309
|
+
otherwise?: DeclaredOutput;
|
|
310
|
+
} | {
|
|
311
|
+
firstNonNull: string;
|
|
312
|
+
} | {
|
|
313
|
+
sum: string;
|
|
314
|
+
} | {
|
|
315
|
+
product: string;
|
|
316
|
+
} | {
|
|
317
|
+
difference: [string, string];
|
|
318
|
+
} | {
|
|
319
|
+
abs: string;
|
|
320
|
+
} | {
|
|
321
|
+
min: string;
|
|
322
|
+
} | {
|
|
323
|
+
max: string;
|
|
324
|
+
};
|
|
325
|
+
|
|
237
326
|
type TypeOf<T> = T extends 'string' ? string : T extends 'number' | 'integer' ? number : T extends 'boolean' ? boolean : T extends 'array' ? unknown[] : T extends 'object' ? Record<string, unknown> : T extends 'null' ? null : T extends 'any' ? unknown : T extends {
|
|
238
327
|
literal: readonly (infer M)[];
|
|
239
328
|
} ? M : T extends readonly (infer B)[] ? TypeOf<B> : unknown;
|
|
@@ -338,6 +427,7 @@ interface OperatorDefinition<P extends ParameterDeclarations = ParameterDeclarat
|
|
|
338
427
|
timeoutParam?: string;
|
|
339
428
|
cache?: true;
|
|
340
429
|
validate?: OperatorValidate;
|
|
430
|
+
analysis?: OperatorAnalysis;
|
|
341
431
|
evaluate: (params: ResolvedParams<P>, context: OperatorContext) => unknown;
|
|
342
432
|
returns?: ExpectedType;
|
|
343
433
|
}
|
|
@@ -372,6 +462,7 @@ interface ValidatedOperatorDefinition {
|
|
|
372
462
|
cache: boolean;
|
|
373
463
|
fingerprint: string;
|
|
374
464
|
validate?: OperatorValidate;
|
|
465
|
+
analysis?: OperatorAnalysis;
|
|
375
466
|
evaluate: OperatorEvaluate;
|
|
376
467
|
returns: ExpectedType;
|
|
377
468
|
}
|
|
@@ -528,13 +619,13 @@ interface Dependencies {
|
|
|
528
619
|
fragments: string[];
|
|
529
620
|
}
|
|
530
621
|
interface ParameterInfo extends ValidatedParameter {
|
|
531
|
-
|
|
622
|
+
hostDefault?: unknown;
|
|
532
623
|
}
|
|
533
624
|
interface OperatorInfo extends Omit<ValidatedOperatorDefinition, typeof VALIDATED_OPERATOR | 'evaluate' | 'validate' | 'deliversLazily' | 'resolution' | 'fingerprint' | 'parameters'> {
|
|
534
625
|
parameters: Record<string, ParameterInfo>;
|
|
535
626
|
hasValidate: boolean;
|
|
536
|
-
|
|
537
|
-
|
|
627
|
+
hostNoCache?: true;
|
|
628
|
+
hostFallback?: unknown;
|
|
538
629
|
}
|
|
539
630
|
interface FragmentInfo {
|
|
540
631
|
name: string;
|
|
@@ -550,7 +641,7 @@ interface FragmentInfo {
|
|
|
550
641
|
declare class FigTree<InstanceOpts extends FigTreeOptions = NoOptions> {
|
|
551
642
|
private state;
|
|
552
643
|
private readonly results;
|
|
553
|
-
readonly version = "3.0.0-preview.
|
|
644
|
+
readonly version = "3.0.0-preview.8";
|
|
554
645
|
constructor(options?: InstanceOpts);
|
|
555
646
|
updateOptions(options?: OptionsUpdate): void;
|
|
556
647
|
clearCache(): void;
|
|
@@ -688,7 +779,7 @@ type InspectNode = {
|
|
|
688
779
|
fallback?: InspectNode;
|
|
689
780
|
timeoutFallback?: Json;
|
|
690
781
|
noCache?: true;
|
|
691
|
-
|
|
782
|
+
hostDefaults?: string[];
|
|
692
783
|
} | {
|
|
693
784
|
kind: 'fragmentCall';
|
|
694
785
|
vars?: NodeMap;
|
|
@@ -822,12 +913,5 @@ interface ShorthandOptions extends NameOptions {
|
|
|
822
913
|
getAsReference?: boolean;
|
|
823
914
|
}
|
|
824
915
|
|
|
825
|
-
interface FallbackCoverage {
|
|
826
|
-
uncovered: (string | number)[][];
|
|
827
|
-
}
|
|
828
|
-
interface FallbackCoverageOptions {
|
|
829
|
-
timeout?: number;
|
|
830
|
-
}
|
|
831
|
-
|
|
832
916
|
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 };
|
|
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 };
|
|
917
|
+
export type { AxiosErrorLike, AxiosLike, BasicType, CacheStore, CacheTraceEvent, CallOptions, CanonicalOptions, CategoryHintMap, CategoryHints, CompiledNullPolicy, ConditionalNullPolicy, Constraints, CoverageFinding, CoveredFinding, DeclaredOutput, Dependencies, EvaluationMode, EvaluationOptions, EvaluationResult, ExpectedType, FailureRule, FailureTest, 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, OperatorAnalysis, 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{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};
|
|
1
|
+
import{j as t,O as a,k as r,l as n,E as o,c as s,m as l,N as u,b as c,R as p,n as m,o as f,p as y,q as h,u as v,w as g,x as w,y as P,z as $,t as k,s as O,g as A,A as q,B as x}from"./chunks/engine.js";export{C as ARRAY,F as FigTree,D as OBJECT,G as compareValues,d as coreOperators,H as deepEqual,e as isOperatorFailure,i as isTruthy}from"./chunks/engine.js";import{a as N,E,k as L,R as S,F as T,l as Q,r as R,d as z,D as J,m as U}from"./chunks/shared.js";export{W as WILDCARD,b as isFigTreeError,j as parsePath}from"./chunks/shared.js";const V=/*#__PURE__*/new Set(["failures","external","output"]),M=/*#__PURE__*/new Set(["code","parameter","when","options","may","overflow"]),B=e=>{if(null===e||["string","number","boolean"].includes(typeof e))return!0;if(!N(e))return!1;const a=Object.keys(e);if(1!==a.length)return!1;const r=e[a[0]];switch(a[0]){case"type":return t(r);case"below":return"number"==typeof r&&Number.isFinite(r);case"empty":case"invalid":return!0===r;case"supplied":return"boolean"==typeof r;case"some":case"not":return B(r);default:return!1}},I=["param","elementOf","kindOf","typeNamedBy","firstNonNull","sum","product","abs","min","max"],Y=e=>void 0===e||"number"==typeof e&&Number.isFinite(e),K=e=>void 0===e||Number.isInteger(e)&&e>=0,X=(e,t,...a)=>t in e&&Object.keys(e).every(e=>e===t||a.includes(e)),Z=(e,a)=>{if(t(e))return!0;if(!N(e))return!1;const r=Object.keys(e);return 1===r.length&&I.includes(r[0])?a(e[r[0]]):"type"in e?(e=>{const{type:t,min:a,max:r,minLength:n}=e;return"number"===t||"integer"===t?X(e,"type","min","max")&&Y(a)&&Y(r)&&!(a>r):("string"===t||"array"===t)&&X(e,"type","minLength")&&K(n)})(e):X(e,"difference")?Array.isArray(e.difference)&&2===e.difference.length&&e.difference.every(a):X(e,"arrayOf","minLength")?K(e.minLength)&&Z(e.arrayOf,a):X(e,"oneOf")?Array.isArray(e.oneOf)&&e.oneOf.length>0&&e.oneOf.every(e=>Z(e,a)):!(!X(e,"byParam","cases","otherwise")||!("cases"in e))&&(a(e.byParam)&&N(e.cases)&&Object.values(e.cases).every(e=>Z(e,a))&&(void 0===e.otherwise||Z(e.otherwise,a)))},_=/[a-z]Default$/,ee=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),te=/*#__PURE__*/new Set(a),ae=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),re=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),ne=(e,t)=>{const[a]=e,r=e.length-1,n=r>0?`${a.message} (+ ${r} more issue${1===r?"":"s"})`:a.message;throw new T({code:E.invalidDefinition,message:n,path:a.path,...void 0!==t?{operator:t}:{},issues:e})};function ie(e){if(r(e))return e;const a=[],i=N(e)?e.name:void 0,d="string"==typeof i?i:void 0,y=(e,t,r,n)=>{a.push({severity:"error",code:e,message:t,path:r,...void 0!==d?{operator:d}:{},...void 0!==n?{parameter:n}:{}})};N(e)||(y(E.invalidDefinition,"a definition must be a plain object",[]),ne(a));const h=e;"string"!=typeof h.name&&y(E.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof h.description&&""!==h.description||y(E.invalidDefinition,"'description' is required and must be non-empty",["description"]),N(h.parameters)||y(E.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof h.evaluate&&y(E.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),a.length>0&&ne(a,d),"string"!=typeof h.category?y(E.invalidDefinition,`'category' is required and must be one of ${[...te].join(", ")}`,["category"]):te.has(h.category)||y(E.invalidDefinition,`'${h.category}' is not a category — expected one of ${[...te].join(", ")}`,["category"]),void 0!==h.alias&&"string"!=typeof h.alias&&y(E.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==h.cache&&!0!==h.cache&&y(E.invalidDefinition,"'cache' must be the literal true",["cache"]),void 0===h.metadata||N(h.metadata)||y(E.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===h.positionalParams||Array.isArray(h.positionalParams)&&!h.positionalParams.some(e=>"string"!=typeof e)||y(E.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==h.timeoutParam&&"string"!=typeof h.timeoutParam&&y(E.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==h.validate&&"function"!=typeof h.validate&&y(E.invalidDefinition,"'validate' must be a function",["validate"]),void 0===h.returns||t(h.returns)||y(E.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const v=(e,t,a)=>{e===o?y(E.invalidDefinition,"the EvaluationData sentinel is legal only as a parameter 'default'",t,a):Array.isArray(e)&&e.forEach((e,r)=>{e===o&&v(e,[...t,r],a)})};for(const[e,t]of Object.entries(h))"parameters"!==e&&"metadata"!==e&&v(t,[e]);const b=(e,t)=>{const a=L(e);a.ok?Q.has(e)&&y(E.reservedName,`'${e}' is a reserved name`,t):y(E.invalidName,`'${e}': ${a.reason}`,t)};"string"==typeof h.name&&b(h.name,["name"]),"string"==typeof h.alias&&b(h.alias,["alias"]);const g=h.parameters,w={};for(const[e,t]of Object.entries(g)){const a=["parameters",e],r=L(e);r.ok?S.has(e)&&y(E.reservedName,`'${e}' is a reserved node key and cannot name a parameter`,a,e):y(E.invalidName,`'${e}': ${r.reason}`,a,e),N(t)?w[e]=t:y(E.invalidDefinition,`the declaration for '${e}' must be a plain object`,a,e)}const j={};for(const[e,a]of Object.entries(w)){const r=["parameters",e],i=e=>[...r,e],d=a;for(const[t,a]of Object.entries(d))"default"!==t&&"metadata"!==t&&v(a,i(t),e);let p=!0;void 0===d.type||t(d.type)||(y(E.invalidDefinition,"'type' must be a metadata-vocabulary type",i("type"),e),p=!1),p&&(j[e]=d.type??"any");let m=!1;if(void 0!==d.constraints){const t=n(d.constraints);t.ok?m=!0:y(E.invalidDefinition,`'constraints' is malformed: expected ${t.expected}, got ${t.actual}`,i("constraints"),e)}void 0!==d.required&&"boolean"!=typeof d.required&&y(E.invalidDefinition,"'required' must be a boolean",i("required"),e),void 0!==d.description&&"string"!=typeof d.description&&y(E.invalidDefinition,"'description' must be a string",i("description"),e),void 0===d.metadata||N(d.metadata)||y(E.invalidDefinition,"'metadata' must be a plain object",i("metadata"),e);const f="default"in d;if(f&&!0===d.required&&y(E.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",i("default"),e),f&&d.default!==o){const t=j[e];if(void 0!==t){const a=s(d.default,t);if(a.ok){if(m&&void 0!==d.constraints){const t=l(d.default,d.constraints);t.ok||y(E.typeCheck,`'default' violates the declared constraints: expected ${t.expected}, got ${t.actual}`,i("default"),e)}}else y(E.typeCheck,`'default' does not satisfy the declared type: expected ${a.expected}, got ${a.actual}`,i("default"),e)}}if(void 0===d.evaluation||ee.has(d.evaluation)||y(E.invalidDefinition,`'evaluation' must be one of ${[...ee].join(", ")}`,i("evaluation"),e),void 0!==d.truthiness&&"boolean"!=typeof d.truthiness&&y(E.invalidDefinition,"'truthiness' must be a boolean",i("truthiness"),e),void 0!==d.over&&"string"!=typeof d.over&&y(E.invalidDefinition,"'over' must be a parameter name",i("over"),e),void 0===d.replacesNullAt||Array.isArray(d.replacesNullAt)&&!d.replacesNullAt.some(e=>"string"!=typeof e)||y(E.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",i("replacesNullAt"),e),void 0!==d.nullPolicy){const t=d.nullPolicy;"function"==typeof t||u.has(t)||y(E.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",i("nullPolicy"),e);const a=j[e];void 0===a||c(a)||y(E.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",i("nullPolicy"),e),!0===d.truthiness&&"propagate"===t&&y(E.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",i("nullPolicy"),e)}if(void 0!==d.elementNullPolicy){u.has(d.elementNullPolicy)||y(E.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",i("elementNullPolicy"),e);const t=j[e];void 0===t||re(t)||y(E.invalidNullPolicy,"'elementNullPolicy' applies to container parameters only",i("elementNullPolicy"),e)}}if(Array.isArray(h.positionalParams)&&h.positionalParams.every(e=>"string"==typeof e)){const e=new Set,t=h.positionalParams;t.forEach((a,r)=>{const n=a.startsWith(p),i=n?a.slice(p.length):a;n&&r!==t.length-1&&y(E.invalidDefinition,`the rest entry '${a}' must be the last positional entry`,["positionalParams",r]),i in w||y(E.invalidDefinition,`positional entry '${a}' names no declared parameter`,["positionalParams",r]),e.has(i)&&y(E.invalidDefinition,`duplicate positional entry '${a}'`,["positionalParams",r]),e.add(i)})}for(const[e,t]of Object.entries(w)){const a=["parameters",e],r="perElement"===t.evaluation;if(void 0!==t.over&&"string"==typeof t.over)if(r){const r=t.over;if(r in w&&r!==e){const t=j[r];void 0===t||ae(t)||y(E.invalidDefinition,`the 'over' target '${r}' must admit an array`,[...a,"over"],e)}else y(E.invalidDefinition,`'over' names no sibling parameter ('${r}')`,[...a,"over"],e)}else y(E.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...a,"over"],e);else r&&y(E.invalidDefinition,"evaluation: 'perElement' requires 'over' to name the iterated sibling",[...a,"evaluation"],e)}for(const[e,t]of Object.entries(w)){if(void 0===t.replacesNullAt)continue;if(!Array.isArray(t.replacesNullAt)||t.replacesNullAt.some(e=>"string"!=typeof e))continue;const a=["parameters",e,"replacesNullAt"];"lazy"!==t.evaluation&&y(E.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",a,e);(t.required??!("default"in t))&&y(E.invalidDefinition,"a 'replacesNullAt' holder must be optional",a,e),"default"in t&&y(E.invalidDefinition,"a 'replacesNullAt' holder may not carry a 'default' — it is presence-sensitive by construction",a,e),t.replacesNullAt.forEach((t,r)=>{t===e?y(E.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...a,r],e):t in w||y(E.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...a,r],e)})}for(const[e,t]of Object.entries(w))_.test(e)&&"lazy"!==t.evaluation&&y(E.invalidDefinition,`'${e}' is named for the '…Default' family, so it must declare evaluation: 'lazy' — add 'replacesNullAt', read it as a LazyValue in the body, or rename it`,["parameters",e,"evaluation"],e);const P=m(w,j,y);if("string"==typeof h.timeoutParam){void 0===w[h.timeoutParam]?y(E.invalidDefinition,`'timeoutParam' names no declared parameter ('${h.timeoutParam}')`,["timeoutParam"]):"integer"!==j[h.timeoutParam]&&y(E.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return void 0!==h.analysis&&((e,t,a)=>{const r=(e,...t)=>a(E.invalidDefinition,e,["analysis",...t]);if(!N(e))return r("'analysis' must be a plain object");for(const t of Object.keys(e))V.has(t)||r(`'${t}' is not an analysis field`,t);const{failures:n,external:i,output:o}=e,s=e=>"string"==typeof e&&Object.hasOwn(t,e);if(void 0!==i&&!0!==i&&r("'external' must be the literal true","external"),void 0===o||Z(o,s)||r("'output' must be a type, or an output declaration naming declared parameters","output"),void 0!==n){if(!Array.isArray(n))return r("'failures' must be an array of rules","failures");!0===i&&r("an external operator declares no 'failures': it may fail whatever its inputs","failures"),n.forEach((e,t)=>{const a=(...e)=>["failures",t,...e];if(!N(e))return r("a rule must be a plain object",...a());for(const t of Object.keys(e))M.has(t)||r(`'${t}' is not a rule field`,...a(t));if("string"==typeof e.code&&""!==e.code||r("a rule's 'code' must be a non-empty string",...a("code")),void 0===e.parameter||s(e.parameter)||r("'parameter' names no declared parameter",...a("parameter")),void 0!==e.when)if(N(e.when))for(const[t,n]of Object.entries(e.when))s(t)?B(n)||r(`the test on '${t}' is malformed`,...a("when",t)):r(`'${t}' is not a declared parameter`,...a("when",t));else r("'when' must be an object of tests",...a("when"));void 0===e.options||N(e.options)||r("'options' must be a plain object",...a("options"));for(const t of["may","overflow"])void 0!==e[t]&&!0!==e[t]&&r(`'${t}' must be the literal true`,...a(t))})}})(h.analysis,w,(e,t,a)=>y(e,t,a)),a.length>0&&ne(a,d),f(h,P)}const oe=e=>new y(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),se=(e,t)=>{const a=t instanceof Error?t.message:String(t),r=t??{},n={driver:e};for(const e of["code","table","column","constraint"])"string"==typeof r[e]&&(n[e]=r[e]);return new y(`${e}: ${a}`,{errorData:n})},le=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class ue{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new y("FetchClient(): this runtime has no global fetch — pass one, new FetchClient(myFetch), or use another client such as new AxiosClient(axios)");this.supplied=e}request=async e=>{const t=this.supplied??globalThis.fetch,a=await t.call(globalThis,e.url,{method:e.method.toUpperCase(),headers:e.headers,...void 0!==e.body?{body:JSON.stringify(e.body)}:{},signal:e.signal}),r=await a.text();if(!a.ok)throw oe({status:a.status,statusText:a.statusText,url:a.url||e.url,payload:pe(r)});return de(r,a.url||e.url,a.status)}}class ce{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new y("AxiosClient(axios): pass the axios import itself — new AxiosClient(axios)")}request=async e=>{try{const t=await this.axios({url:e.url,method:e.method,headers:e.headers,...void 0!==e.body?{data:e.body}:{},signal:e.signal});return""===t.data||void 0===t.data?null:t.data}catch(t){if(this.axios.isAxiosError(t)&&t.response)throw oe({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const de=(e,t,a)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new y(`response was not JSON (${a}): ${t}`,{errorData:{status:a,url:t,response:le(e)}})}},pe=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return le(e)}},me=/^https?:\/\//i,fe=(e,t,a)=>{const r=me.test(e)?e:ye(a,e),n=he(t),i=""===n?r:`${r}${r.includes("?")?"&":"?"}${n}`;try{new URL(i)}catch{throw new y(`'${i}' is not a valid URL`,{code:E.typeCheck})}return i},ye=(e,t)=>{if(void 0===e||""===e)throw new y(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:E.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},he=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[a,r]of Object.entries(e))null!=r&&t.append(a,ge(r,`query['${a}']`,"query"));return t.toString()},ve=(...e)=>{const t={};for(const a of e)if(void 0!==a)for(const[e,r]of Object.entries(a))null!=r?t[e]=ge(r,`headers['${e}']`,"header"):delete t[e];return t},be=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),ge=(e,t,a)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return v(e);throw new y(`${t} is ${g(e)} — a ${a} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:E.typeCheck})},we=e=>({method:e.method,url:e.url,headers:Object.fromEntries(Object.entries(e.headers).sort(([e],[t])=>e<t?-1:e>t?1:0)),...void 0!==e.body?{body:e.body}:{}}),je=e=>Array.isArray(e)?e.length>0:N(e)?Object.keys(e).length>0:null!=e,Pe=(e,t)=>{if(void 0===t)return e;const a=R(e,h(t));return a.found?void 0===a.value?null:a.value:null},$e=(e,t)=>{if(!N(e))throw new y("a row was not an object");const a=Object.values(e);if(1!==a.length)throw new y(`shape: '${t}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:E.typeCheck});return a[0]},ke={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},De={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},Oe=e=>P({name:"http",category:"io",description:"One HTTP request — GET or POST — returning the parsed JSON response",parameters:{url:{type:"string",description:"A full http(s) URL is used verbatim; anything else — including an empty string — joins http.baseEndpoint"},method:{type:{literal:["get","post"]},default:"get",description:"Lowercase; the mutating verbs are deliberately absent — an expression is a read"},query:{type:"object",required:!1,elementNullPolicy:"value",description:"Query-string pairs; a null value omits its pair, a composite one is an error"},body:{type:["string","number","boolean","array","object"],required:!1,description:"The JSON payload; a whole-null body means NO body, while nulls inside one are JSON nulls"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over the http.headers option per key; a null value removes an inherited pair"},returnPath:De,timeout:ke},positionalParams:["url"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e,method:t,body:a})=>[...$(e,"returnPath"),...xe(t,a)],evaluate:async({url:t,method:a,query:r,body:n,headers:i,returnPath:o},s)=>{if("get"===a&&void 0!==n)throw new y("a GET carries no body — did you mean method: 'post'?",{code:E.typeCheck});const l={method:a,url:fe(t,r,s.options.http?.baseEndpoint),headers:ve(be(void 0!==n),s.options.http?.headers,i),...void 0!==n?{body:n}:{}},u=await s.cache.memo(we(l),()=>(Le(s,l),e.request({...l,signal:s.signal})));return Pe(u,o)}}),Ae=e=>P({name:"graphQL",category:"io",description:"One GraphQL query — a POST of { query, variables } — returning the data field",parameters:{query:{type:"string",description:"The GraphQL document — the protocol’s own word, as sql.query is"},variables:{type:"object",required:!1,elementNullPolicy:"value",description:"Query variables; a null value is CARRIED as JSON null, a nullable argument being meaningful GraphQL"},url:{type:"string",required:!1,description:"Per-node endpoint override; unset means the graphQL.endpoint option"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over http.headers then graphQL.headers; a null value removes a pair"},returnPath:De,timeout:ke},positionalParams:["query","variables"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e})=>$(e,"returnPath"),evaluate:async({query:t,variables:a,url:r,headers:n,returnPath:i},o)=>{const s=r??o.options.graphQL?.endpoint;if(void 0===s)throw new y("no endpoint — supply url, or set the graphQL.endpoint option");const l={method:"post",url:fe(s,void 0,o.options.http?.baseEndpoint),headers:ve(be(!0),o.options.http?.headers,o.options.graphQL?.headers,n),body:{query:t,...je(a)?{variables:a}:{}}},u=await o.cache.memo(we(l),async()=>(Le(o,l),(e=>{if(!N(e))throw new y("the GraphQL response was not an object");const t=e.errors;if(Array.isArray(t)&&t.length>0){const e=t[0]?.message;throw new y(`the GraphQL response carried ${t.length} error${1===t.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:t}})}if(!("data"in e))throw new y("the GraphQL response carried neither data nor errors");return e.data??null})(await e.request({...l,signal:o.signal}))));return Pe(u,i)}}),qe=e=>P({name:"sql",category:"io",description:"One SQL query against the registered connection. Expressions are READS — give the connection a read-only role and run mutations host-side",parameters:{query:{type:"string",description:"SQL text with the driver’s own placeholders — FigTree never parses SQL"},values:{type:["array","object"],required:!1,elementNullPolicy:"value",description:"Bind values — positional as an array, named as an object; a null binds SQL NULL"},shape:{type:{literal:["rows","firstRow","column","firstValue"]},default:"rows",description:"rows: every row object; firstRow: the first; column: one column’s values; firstValue: one scalar"},noRowDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The answer when firstRow / firstValue find no row — never for rows / column, never on failure"},timeout:ke},positionalParams:["query","...values"],timeoutParam:"timeout",cache:!0,returns:"any",evaluate:async({query:t,values:a,shape:r,noRowDefault:n},i)=>{const o={text:t,...je(a)?{values:a}:{}};return(async(e,t,a)=>{switch(t){case"rows":return e;case"firstRow":return 0===e.length?a.evaluate():e[0];case"column":return e.map(e=>$e(e,"column"));case"firstValue":return 0===e.length?a.evaluate():$e(e[0],"firstValue")}})(await i.cache.memo(o,()=>(i.trace.note({type:"query",text:o.text}),e.query({...o,signal:i.signal}))),r,n)}}),xe=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],Ne=(e=new ue)=>[w(Oe(e)),w(Ae(e))],Ee=e=>[w(qe(e))],Le=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class Ce{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new y("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new y("postgres takes positional binds ($1, $2, …) — an object of named binds needs a driver that supports them");try{const t=await this.client.query({text:e.text,...void 0!==e.values?{values:e.values}:{}});return t?.rows??[]}catch(e){throw se("postgres",e)}}}class Se{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new y("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw se("sqlite",e)}}}const Te=e=>Qe(e,0,new Set),Qe=(e,t,a)=>{if(null===e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e&&Number.isFinite(e)&&!Object.is(e,-0))return e;if("object"!=typeof e)return Re(e);if(!Array.isArray(e)&&!z(e))return Fe(e);if(a.has(e))return"[circular]";if(t>=J)return"[too deep]";a.add(e);const r=Array.isArray(e)?Array.from(e,e=>Qe(e,t+1,a)):Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Qe(r,t+1,a)]));return a.delete(e),r},Re=e=>{switch(typeof e){case"function":return""===e.name?"[function]":`[function ${e.name}]`;case"symbol":return`[${String(e)}]`;case"bigint":return`[bigint ${e}]`;case"number":return Object.is(e,-0)?"[-0]":`[${e}]`;default:return"[undefined]"}},Fe=e=>{const t=ze(e);try{const a=e.toJSON;if("function"==typeof a){const r=a.call(e);if("string"==typeof r)return`[${t} ${r}]`}}catch{}return`[${t}]`},ze=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},Ge=e=>{const t=new Map;for(const a of e.holes)void 0!==a.timeoutFallback&&t.set(a.node,a.timeoutFallback);const a=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])),r=e=>{const a=t.get(e);return void 0===a?{}:{timeoutFallback:Te(a.value)}},n=e=>{const t={order:e.order,kind:e.kind,path:k(e.path)},i="vars"in e&&void 0!==e.vars?{vars:a(e.vars)}:{};switch(e.kind){case"constant":return{...t,kind:e.kind,value:Te(e.value)};case"reference":return{...t,kind:e.kind,reference:U(e.binding??e.namespace,e.segments),authored:e.raw,...void 0===e.binding?{}:{binding:e.binding}};case"operator":return{...t,kind:e.kind,...i,operator:e.name,params:a(e.params),...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache},...void 0===e.entry.hostDefaults?{}:{hostDefaults:Object.keys(e.entry.hostDefaults)}};case"fragmentCall":return{...t,kind:e.kind,...i,fragment:e.name,resolved:void 0!==e.entry,argumentsMode:e.argumentsMode,...void 0===e.parameters?{}:{parameters:"dynamic"===e.argumentsMode?n(e.parameters):a(e.parameters)},...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache}};case"skeleton":{const a=O(e.skeleton,e.holes,e.holes.map(()=>"<hole>"));return{...t,kind:e.kind,...i,shape:Te(a),holes:e.holes.map(e=>({at:[...e.at],node:n(e.node)}))}}case"elements":return{...t,kind:e.kind,elements:e.nodes.map(n)};case"entries":return{...t,kind:e.kind,...i,entries:a(e.entries)};case"invalid":return{...t,kind:e.kind,raw:Te(e.raw)}}};return n(e.root)},Je=(e,t)=>{const a=A(e,t);if(void 0===a)throw new TypeError("inspect() takes a CompiledExpression — the handle fig.compile() returns");const{expression:r,artifact:n,options:i}=a;return{version:q,expression:Te(r),options:Ve(i),canonicalForm:Ge(n),issues:x(n,i,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:n.timeoutShielded,nodeCount:n.nodeCount,maxDepth:n.maxDepth,dependencies:Ie(n.dependencies),own:{nodeCount:n.own.nodeCount,maxDepth:n.own.maxDepth,dependencies:Ie(n.own.dependencies)}}},Ue="[supplied]",Ve=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Me(e,t)])),Me=(e,t)=>{switch(e){case"data":{const e="object"==typeof t&&null!==t?Object.keys(t).length:0;return`[supplied: ${e} top-level key${1===e?"":"s"}]`}case"signal":return Ue;case"http":case"graphQL":return Be(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):Te(e));case"cache":return Be(t,"store",()=>Ue);default:return Te(t)}},Be=(e,t,a)=>"object"==typeof e&&null!==e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,r])=>[e,e===t?a(r):Te(r)])):Te(e),Ie=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{ce as AxiosClient,E as ErrorCodes,o as EvaluationData,ue as FetchClient,T as FigTreeError,a as OPERATOR_CATEGORIES,y as OperatorFailure,Ce as PostgresConnection,Se as SQLiteConnection,ie as defineOperator,Ne as httpOperators,Je as inspect,v as renderText,R as resolvePath,Ee as sqlOperators,q as version};
|