@opencorestack/opengridx 3.7.0 → 3.7.1
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/CHANGELOG.md +22 -0
- package/dist/ai.cjs +3 -3
- package/dist/ai.cjs.map +1 -1
- package/dist/ai.es.js +3 -3
- package/dist/ai.es.js.map +1 -1
- package/dist/opengridx.css +1 -1
- package/dist/opengridx.es.js +3195 -3119
- package/dist/opengridx.es.js.map +1 -1
- package/dist/opengridx.umd.js +15 -15
- package/dist/opengridx.umd.js.map +1 -1
- package/lib/components/DataGrid/DataGrid.css +0 -3
- package/lib/components/ListView/ListView.css +4 -4
- package/lib/hooks/core/useLayout.ts +34 -24
- package/lib/styles/base/reset.css +5 -3
- package/lib/utils/export/exportShared.ts +22 -4
- package/lib/utils/export/index.ts +8 -4
- package/lib/utils/filtering/index.ts +8 -2
- package/lib/utils/parsing.ts +24 -1
- package/lib/utils/values.ts +31 -0
- package/package.json +1 -1
package/dist/ai.es.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const K=new Set;function de(e,t,r){process.env.NODE_ENV==="production"||K.has(e)||(K.add(e),console.warn(`[OpenGridX] ${t}.`,r))}function pe(e,t,r){const n=e[t];if(!r?.valueGetter)return{value:n};try{return{value:r.valueGetter({row:e,field:t,value:n})}}catch(i){return{value:void 0,error:i??new Error("valueGetter failed")}}}function ge(e,t,r){if(!r?.valueGetter)return e[t];const{value:n,error:i}=pe(e,t,r);return i!==void 0&&de(`valueGetter:${t}`,`valueGetter for column "${t}" threw; the value is read as undefined`,i),n}const me=/^(\d{4})-(\d{2})-(\d{2})$/;function Q(e){if(e==null)return null;let t;if(e instanceof Date)t=e;else if(typeof e=="number")t=new Date(e);else if(typeof e=="string"){const r=e.trim();if(r==="")return null;const n=me.exec(r);if(n){const i=Number(n[1]),o=Number(n[2])-1,s=Number(n[3]);if(t=new Date(i,o,s),t.getMonth()!==o||t.getDate()!==s)return null}else t=new Date(r)}else return null;return Number.isNaN(t.getTime())?null:t}function ye(e){const t=Q(e);if(!t)return"";const r=String(t.getFullYear()).padStart(4,"0"),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${r}-${n}-${i}`}function he(e){switch(e){case"number":return["=","!=",">",">=","<","<=","isEmpty","isNotEmpty"];case"date":return["is","not","after","onOrAfter","before","onOrBefore","isEmpty","isNotEmpty"];case"boolean":return["is"];case"singleSelect":return["isAnyOf","is","not"];default:return["contains","equals","startsWith","endsWith","isEmpty","isNotEmpty"]}}const be=["sum","avg","count","min","max","unique"],W=["sum","avg","count","min","max"],Z=["isEmpty","isNotEmpty"],q=3,I=["filter","sort","grouping","aggregation","pivot","columnVisibility"],L={filter:"filterModel",sort:"sortModel",grouping:"rowGroupingModel",aggregation:"aggregationModel",pivot:"pivotModel",columnVisibility:"columnVisibilityModel"};function v(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function b(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ee(e){const t=Array.isArray(e?.include)?e.include:I,r=Array.isArray(e?.exclude)?e.exclude:[];return I.filter(n=>t.includes(n)&&!r.includes(n))}function J(e){if(!Array.isArray(e))return[];const t=new Set,r=[];for(const n of e){if(!b(n))continue;const i=n.field;typeof i!="string"||i===""||i.startsWith("__")||n.isSpacer===!0||t.has(i)||(t.add(i),r.push(n))}return r}function te(e){return he(e.type)}const re=e=>e.filterable!==!1,ne=e=>e.sortable!==!1,k=e=>e.groupable!==!1,ie=e=>e.hideable!==!1;function S(e,t=be){if(e.aggregable===!1)return[];const r=e.type==="number"||e.aggregable===!0?t:t.filter(i=>i==="count"),n=e.availableAggregationFunctions;return Array.isArray(n)?r.filter(i=>n.includes(i)):[...r]}function $e(e){const t=[];if(!Array.isArray(e.valueOptions))return t;for(const r of e.valueOptions){const n=r!==null&&typeof r=="object"?r.value:r;(typeof n=="string"||typeof n=="number"&&Number.isFinite(n))&&!t.includes(n)&&t.push(n)}return t}const ve="OpenGridX grid state",we=10;function N(e){const t=typeof e.headerName=="string"&&e.headerName!==""?e.headerName:e.field,r=typeof e.description=="string"&&e.description!==""?` (${e.description})`:"";return`${t}${r}`}function M(e,t,r){return r.descriptions?{...e,description:t}:e}function Me(e,t){return!t.examples||!Array.isArray(e.aiExamples)?[]:e.aiExamples.filter(r=>typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)).slice(0,we)}function Ae(e,t){let r;switch(e.type){case"number":r={type:"number"};break;case"date":r={type:"string",format:"date"};break;case"boolean":r={type:"boolean"};break;case"singleSelect":{const i=$e(e),o=i.length>0?{enum:i}:{type:"string"};r={anyOf:[o,{type:"array",items:o}]};break}default:r={type:"string"}}const n=Me(e,t);return n.length>0?{...r,examples:n}:r}function Oe(e,t){const r=te(e),n=r.filter(s=>Z.includes(s)),i=e.type==="singleSelect"?"; isAnyOf takes an array":"",o=n.length>0?`${n.join(" and ")} take no value${i}`:i.slice(2);return M({type:"object",properties:{field:{const:e.field},operator:{enum:r},value:Ae(e,t)},required:["field","operator"],additionalProperties:!1},o?`${N(e)}: ${o}`:N(e),t)}function Fe(e,t,r){const n=e.filter(re),i={},o={enum:["and","or"]};if(n.length>0){r.filterItem={oneOf:n.map(s=>Oe(s,t))};for(let s=q;s>=1;s--){const l=s===q?{$ref:"#/$defs/filterItem"}:{anyOf:[{$ref:"#/$defs/filterItem"},{$ref:`#/$defs/filterGroup${s+1}`}]};r[`filterGroup${s}`]={type:"object",properties:{logicOperator:o,items:{type:"array",items:l}},required:["logicOperator","items"],additionalProperties:!1}}i.items={type:"array",items:{anyOf:[{$ref:"#/$defs/filterItem"},{$ref:"#/$defs/filterGroup1"}]}},i.logicOperator=o}return i.quickFilterValues=M({type:"array",items:{type:"string"}},"Words a row must contain, in any column",t),{type:"object",properties:i,additionalProperties:!1}}function U(e){return{enum:e.map(t=>t.field)}}function Se(e,t,r,n){switch(e){case"filter":return Fe(t,r,n);case"sort":{const i=t.filter(ne);return i.length===0?null:M({type:"array",items:{type:"object",properties:{field:U(i),sort:{enum:["asc","desc"]}},required:["field","sort"],additionalProperties:!1}},"Most significant first",r)}case"grouping":{const i=t.filter(k);return i.length===0?null:M({type:"array",items:U(i),uniqueItems:!0},"Outermost first",r)}case"aggregation":{const i={};for(const o of t){const s=S(o);s.length>0&&(i[o.field]=M({enum:s},N(o),r))}return Object.keys(i).length===0?null:{type:"object",properties:i,additionalProperties:!1}}case"pivot":{const i=t.filter(k),o=t.map(l=>({col:l,fns:S(l,W)})).filter(l=>l.fns.length>0).map(({col:l,fns:a})=>M({type:"object",properties:{field:{const:l.field},aggFn:{enum:a}},required:["field","aggFn"],additionalProperties:!1},N(l),r));if(i.length===0||o.length===0)return null;const s={type:"array",items:U(i),uniqueItems:!0};return{type:"object",properties:{rowFields:s,columnFields:s,valueFields:{type:"array",items:{oneOf:o}}},required:["rowFields","columnFields","valueFields"],additionalProperties:!1}}case"columnVisibility":{const i={};for(const o of t.filter(ie))i[o.field]=M({type:"boolean"},N(o),r);return Object.keys(i).length===0?null:M({type:"object",properties:i,additionalProperties:!1},"false hides a column",r)}}}function B(e,t={}){const r={descriptions:t.descriptions!==!1,examples:t.examples!==!1},n=J(e),i={},o={};for(const l of ee(t)){const a=Se(l,n,r,i);a&&(o[L[l]]=a)}const s={$schema:"https://json-schema.org/draft/2020-12/schema",schemaVersion:1,title:ve,type:"object",properties:o,additionalProperties:!1};return r.descriptions&&(s.description="Grid state to apply. Include only the parts the user asked to change."),Object.keys(i).length>0&&(s.$defs=i),s}const je=Symbol.for("opengridx.ai.validated");function _(e){return Object.defineProperty(e,je,{value:!0,enumerable:!1}),e}const O={ok:!1},$=e=>({ok:!0,value:e}),xe=/^\d+(?:\.\d*)?(?:e[+-]?\d+)?$/i,Ee=/^\.\d+(?:e[+-]?\d+)?$/i,ke=/^\d{1,3}(?:,\d{3})+(?:\.\d*)?$/,Ne=/[\p{Sc}\s]/gu;function Ge(e){let t=e.replace(Ne,"");if(t==="")return e.trim()===""?$(null):O;let r=!1;t.startsWith("(")&&t.endsWith(")")&&(r=!0,t=t.slice(1,-1)),(t.startsWith("-")||t.startsWith("+")||t.startsWith("\u2212"))&&(t[0]!=="+"&&(r=!r),t=t.slice(1));let n=!1;if(t.endsWith("%")&&(n=!0,t=t.slice(0,-1)),ke.test(t))t=t.split(",").join("");else if(!xe.test(t)&&!Ee.test(t))return O;let i=Number(t);return Number.isFinite(i)?(n&&(i/=100),r&&(i=-i),$(i)):O}function Ve(e,t){const r=e.trim();if(r==="")return $(null);const n=Q(r);return n?$(n):O}const qe=new Set(["true","yes","1"]),_e=new Set(["false","no","0"]);function Pe(e,t){const r=e.trim().toLowerCase();return r===""?$(null):qe.has(r)?$(!0):_e.has(r)?$(!1):O}function Ce(e,t){const r=e.trim();if(r==="")return $(null);if(!t||t.length===0)return O;const n=r.toLowerCase();for(const i of t){const o=typeof i=="object"?i.value:i;if(String(o).toLowerCase()===n)return $(o)}for(const i of t)if(typeof i=="object"&&i.label.toLowerCase()===n)return $(i.value);return O}const p=e=>({ok:!0,value:e}),w={ok:!1,reason:"invalidValue"},P=e=>e.ok?p(e.value):w;function C(e){return e==null||typeof e=="string"&&e.trim()===""}function De(e){return e==null?p(""):typeof e=="string"?p(e):typeof e=="number"||typeof e=="boolean"?p(String(e)):w}function Te(e){return C(e)?p(null):typeof e=="number"?Number.isFinite(e)?p(e):w:typeof e!="string"?w:P(Ge(e))}function Re(e){return C(e)?p(null):e instanceof Date?Number.isNaN(e.getTime())?w:p(e):typeof e=="number"?Number.isFinite(e)?p(new Date(e)):w:typeof e!="string"?w:P(Ve(e))}function oe(e){return C(e)?p(null):typeof e=="boolean"?p(e):typeof e!="string"&&typeof e!="number"?w:P(Pe(String(e)))}function We(e,t){if(C(e))return p(null);if(typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return w;const r=t.valueOptions;return!r||r.length===0?p(e):P(Ce(String(e),r))}function Ie(e,t){switch(t.type){case"number":return Te(e);case"date":return Re(e);case"boolean":return oe(e);case"singleSelect":return We(e,t);default:return De(e)}}const X=200,Le=100;function u(e,t,r){return e.errors.length<Le&&e.errors.push({path:t,message:r}),null}function f(e){return typeof e=="string"?JSON.stringify(e.slice(0,60)):e===null||typeof e!="object"?String(e):Array.isArray(e)?"a list":"an object"}function se(e){return typeof e=="string"?e.trim().toLowerCase():null}function H(e){return Object.keys(e).filter(t=>t!=="__proto__")}function j(e,t,r,n,i){const o=typeof t=="string"?e.byField.get(t):void 0;return o?n(o)?o:u(e,r,`Field ${f(t)} cannot be ${i}`):u(e,r,`Unknown field ${f(t)}`)}function x(e,t,r){if(t==null)return[];const n=Array.isArray(t)?t:[t];return n.length>X&&u(e,r,`Only the first ${X} entries are read`),n.slice(0,X)}function G(e,t,r,n){const i=se(t);return n.find(o=>o.toLowerCase()===i)??u(e,r,`${f(t)} is not one of ${n.join(", ")}`)}function le(e,t,r,n){const i=Ie(t,r);if(!i.ok)return u(e,n,`${f(t)} is not a valid ${r.type??"string"} value`);const o=i.value instanceof Date?ye(i.value):i.value;return o==null||o===""?u(e,n,"Missing value"):{v:o}}function Je(e,t,r){const n=j(e,t.field,`${r}.field`,re,"filtered");if(!n)return null;const i=G(e,t.operator,`${r}.operator`,te(n));if(i===null)return null;const o={field:n.field,operator:i};if(Z.includes(o.operator))return o;const s=v(t,"value")?t.value:void 0;if(o.operator==="isAnyOf"){const a=[];return x(e,s,`${r}.value`).forEach((c,A)=>{const g=le(e,c,n,`${r}.value[${A}]`);g&&!a.includes(g.v)&&a.push(g.v)}),a.length===0?u(e,`${r}.value`,"No valid values"):(o.value=a,o)}if(Array.isArray(s))return u(e,`${r}.value`,"Expected one value, not a list");const l=le(e,s,n,`${r}.value`);return l?(o.value=l.v,o):null}function ae(e,t,r){return t===void 0?null:G(e,t,r,["and","or"])}function ue(e,t,r,n){const i=[];return x(e,t,r).forEach((o,s)=>{const l=`${r}[${s}]`;if(!b(o))u(e,l,`Expected a filter, got ${f(o)}`);else if(v(o,"items")||v(o,"logicOperator")){if(n>=q){u(e,l,`Groups nest at most ${q} levels`);return}const a=ue(e,o.items,`${l}.items`,n+1);a.length===0?u(e,l,"Empty group removed"):i.push({logicOperator:ae(e,o.logicOperator,`${l}.logicOperator`)??"and",items:a})}else{const a=Je(e,o,l);a&&i.push(a)}}),i}function Ue(e,t,r){const n={};v(t,"items")&&(n.items=ue(e,t.items,`${r}.items`,0));const i=ae(e,t.logicOperator,`${r}.logicOperator`);return i&&(n.logicOperator=i),v(t,"quickFilterValues")&&(n.quickFilterValues=[],x(e,t.quickFilterValues,`${r}.quickFilterValues`).forEach((o,s)=>{const l=typeof o=="string"||typeof o=="number"?String(o).trim():null;l===null?u(e,`${r}.quickFilterValues[${s}]`,`Expected text, got ${f(o)}`):l!==""&&n.quickFilterValues?.push(l)})),n}function Be(e,t,r){const n=[];return x(e,t,r).forEach((i,o)=>{const s=`${r}[${o}]`;if(!b(i))return u(e,s,`Expected { field, sort }, got ${f(i)}`);const l=j(e,i.field,`${s}.field`,ne,"sorted"),a=l&&G(e,i.sort,`${s}.sort`,["asc","desc"]);!l||!a||(n.some(c=>c.field===l.field)?u(e,s,`${f(l.field)} is sorted twice`):n.push({field:l.field,sort:a}))}),n}function Y(e,t,r,n,i){const o=[];return x(e,t,r).forEach((s,l)=>{const a=j(e,s,`${r}[${l}]`,n,i);a&&!o.includes(a.field)&&o.push(a.field)}),o}const Xe=e=>S(e).length>0,He=e=>S(e,W).length>0;function Ye(e,t,r){const n={};for(const i of H(t)){if(se(t[i])==="none")continue;const o=j(e,i,`${r}.${i}`,Xe,"aggregated"),s=o&&G(e,t[i],`${r}.${i}`,S(o));o&&s&&(n[o.field]=s)}return n}function ze(e,t,r){const n=[];return x(e,t.valueFields,`${r}.valueFields`).forEach((i,o)=>{const s=`${r}.valueFields[${o}]`;if(!b(i))return u(e,s,`Expected { field, aggFn }, got ${f(i)}`);const l=j(e,i.field,`${s}.field`,He,"a pivot value"),a=l&&G(e,i.aggFn,`${s}.aggFn`,S(l,W));l&&a&&!n.some(c=>c.field===l.field&&c.aggFn===a)&&n.push({field:l.field,aggFn:a})}),{rowFields:Y(e,t.rowFields,`${r}.rowFields`,k,"a pivot label"),columnFields:Y(e,t.columnFields,`${r}.columnFields`,k,"a pivot label"),valueFields:n}}function Ke(e,t,r){const n={};for(const i of H(t)){const o=j(e,i,`${r}.${i}`,ie,"hidden"),s=oe(t[i]);o&&(s.ok&&s.value!==null?n[o.field]=s.value:u(e,`${r}.${i}`,`Expected true or false, got ${f(t[i])}`))}return n}function Qe(e,t,r,n,i){t==="sort"?i.sortModel=Be(e,r,n):t==="grouping"?i.rowGroupingModel=Y(e,r,n,k,"grouped"):b(r)?t==="filter"?i.filterModel=Ue(e,r,n):t==="aggregation"?i.aggregationModel=Ye(e,r,n):t==="pivot"?i.pivotModel=ze(e,r,n):i.columnVisibilityModel=Ke(e,r,n):u(e,n,`Expected an object, got ${f(r)}`)}function z(e,t,r={}){const n=Ze(e,t,r);return _(n.state),_(n)}function Ze(e,t,r){const n={errors:[],byField:new Map},i={};try{for(const l of J(t))n.byField.set(l.field,l);let o=e;if(typeof e=="string")try{o=JSON.parse(e)}catch{return u(n,"","Not valid JSON"),{state:i,errors:n.errors}}if(!b(o))return u(n,"",`Expected an object, got ${f(o)}`),{state:i,errors:n.errors};const s=ee(r);for(const l of H(o)){const a=I.find(c=>L[c]===l);l==="schemaVersion"?o[l]!==1&&u(n,l,`Unsupported schemaVersion ${f(o[l])}`):l==="message"?typeof o[l]!="string"&&u(n,l,`Expected text, got ${f(o[l])}`):a?s.includes(a)?Qe(n,a,o[l],l,i):u(n,l,"Part not allowed"):u(n,l,"Unknown part")}}catch{return u(n,"","Could not read the input"),{state:{},errors:n.errors}}return{state:i,errors:n.errors}}const V="```";function D(){return typeof DOMException=="function"?new DOMException("The operation was aborted.","AbortError"):Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function et(e){const t=e.trim();if(t.startsWith("{"))return{json:t,message:""};const r=e.indexOf(V),n=r<0?-1:e.indexOf(`
|
|
2
|
-
`,r+V.length),
|
|
1
|
+
const K=new Set;function de(e,t,r){process.env.NODE_ENV==="production"||K.has(e)||(K.add(e),console.warn(`[OpenGridX] ${t}.`,r))}function pe(e,t,r){const n=e[t];if(!r?.valueGetter)return{value:n};try{return{value:r.valueGetter({row:e,field:t,value:n})}}catch(o){return{value:void 0,error:o??new Error("valueGetter failed")}}}function ge(e,t,r){if(!r?.valueGetter)return e[t];const{value:n,error:o}=pe(e,t,r);return o!==void 0&&de(`valueGetter:${t}`,`valueGetter for column "${t}" threw; the value is read as undefined`,o),n}const me=/^(\d{4})-(\d{2})-(\d{2})$/;function Q(e){if(e==null)return null;let t;if(e instanceof Date)t=e;else if(typeof e=="number")t=new Date(e);else if(typeof e=="string"){const r=e.trim();if(r==="")return null;const n=me.exec(r);if(n){const o=Number(n[1]),i=Number(n[2])-1,s=Number(n[3]);if(t=new Date(o,i,s),t.getMonth()!==i||t.getDate()!==s)return null}else{if(!$e(r))return null;t=new Date(r)}}else return null;return Number.isNaN(t.getTime())?null:t}const ye=["january","february","march","april","may","june","july","august","september","october","november","december","monday","tuesday","wednesday","thursday","friday","saturday","sunday"],he=new Set(["t","z","am","pm","gmt","utc","sept"]);function be(e){return he.has(e)?!0:e.length>=3&&ye.some(t=>t.startsWith(e))}function $e(e){let t="";for(let r=0;r<=e.length;r++){const n=r<e.length?e[r].toLowerCase():"";if(n>="a"&&n<="z"){t+=n;continue}if(t!==""&&!be(t))return!1;t=""}return!0}function ve(e){const t=Q(e);if(!t)return"";const r=String(t.getFullYear()).padStart(4,"0"),n=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0");return`${r}-${n}-${o}`}function we(e){switch(e){case"number":return["=","!=",">",">=","<","<=","isEmpty","isNotEmpty"];case"date":return["is","not","after","onOrAfter","before","onOrBefore","isEmpty","isNotEmpty"];case"boolean":return["is"];case"singleSelect":return["isAnyOf","is","not"];default:return["contains","equals","startsWith","endsWith","isEmpty","isNotEmpty"]}}const Me=["sum","avg","count","min","max","unique"],R=["sum","avg","count","min","max"],Z=["isEmpty","isNotEmpty"],q=3,L=["filter","sort","grouping","aggregation","pivot","columnVisibility"],I={filter:"filterModel",sort:"sortModel",grouping:"rowGroupingModel",aggregation:"aggregationModel",pivot:"pivotModel",columnVisibility:"columnVisibilityModel"};function v(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function b(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ee(e){const t=Array.isArray(e?.include)?e.include:L,r=Array.isArray(e?.exclude)?e.exclude:[];return L.filter(n=>t.includes(n)&&!r.includes(n))}function J(e){if(!Array.isArray(e))return[];const t=new Set,r=[];for(const n of e){if(!b(n))continue;const o=n.field;typeof o!="string"||o===""||o.startsWith("__")||n.isSpacer===!0||t.has(o)||(t.add(o),r.push(n))}return r}function te(e){return we(e.type)}const re=e=>e.filterable!==!1,ne=e=>e.sortable!==!1,k=e=>e.groupable!==!1,oe=e=>e.hideable!==!1;function j(e,t=Me){if(e.aggregable===!1)return[];const r=e.type==="number"||e.aggregable===!0?t:t.filter(o=>o==="count"),n=e.availableAggregationFunctions;return Array.isArray(n)?r.filter(o=>n.includes(o)):[...r]}function Ae(e){const t=[];if(!Array.isArray(e.valueOptions))return t;for(const r of e.valueOptions){const n=r!==null&&typeof r=="object"?r.value:r;(typeof n=="string"||typeof n=="number"&&Number.isFinite(n))&&!t.includes(n)&&t.push(n)}return t}const Oe="OpenGridX grid state",Fe=10;function N(e){const t=typeof e.headerName=="string"&&e.headerName!==""?e.headerName:e.field,r=typeof e.description=="string"&&e.description!==""?` (${e.description})`:"";return`${t}${r}`}function M(e,t,r){return r.descriptions?{...e,description:t}:e}function je(e,t){return!t.examples||!Array.isArray(e.aiExamples)?[]:e.aiExamples.filter(r=>typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)).slice(0,Fe)}function Se(e,t){let r;switch(e.type){case"number":r={type:"number"};break;case"date":r={type:"string",format:"date"};break;case"boolean":r={type:"boolean"};break;case"singleSelect":{const o=Ae(e),i=o.length>0?{enum:o}:{type:"string"};r={anyOf:[i,{type:"array",items:i}]};break}default:r={type:"string"}}const n=je(e,t);return n.length>0?{...r,examples:n}:r}function xe(e,t){const r=te(e),n=r.filter(s=>Z.includes(s)),o=e.type==="singleSelect"?"; isAnyOf takes an array":"",i=n.length>0?`${n.join(" and ")} take no value${o}`:o.slice(2);return M({type:"object",properties:{field:{const:e.field},operator:{enum:r},value:Se(e,t)},required:["field","operator"],additionalProperties:!1},i?`${N(e)}: ${i}`:N(e),t)}function Ee(e,t,r){const n=e.filter(re),o={},i={enum:["and","or"]};if(n.length>0){r.filterItem={oneOf:n.map(s=>xe(s,t))};for(let s=q;s>=1;s--){const l=s===q?{$ref:"#/$defs/filterItem"}:{anyOf:[{$ref:"#/$defs/filterItem"},{$ref:`#/$defs/filterGroup${s+1}`}]};r[`filterGroup${s}`]={type:"object",properties:{logicOperator:i,items:{type:"array",items:l}},required:["logicOperator","items"],additionalProperties:!1}}o.items={type:"array",items:{anyOf:[{$ref:"#/$defs/filterItem"},{$ref:"#/$defs/filterGroup1"}]}},o.logicOperator=i}return o.quickFilterValues=M({type:"array",items:{type:"string"}},"Words a row must contain, in any column",t),{type:"object",properties:o,additionalProperties:!1}}function U(e){return{enum:e.map(t=>t.field)}}function ke(e,t,r,n){switch(e){case"filter":return Ee(t,r,n);case"sort":{const o=t.filter(ne);return o.length===0?null:M({type:"array",items:{type:"object",properties:{field:U(o),sort:{enum:["asc","desc"]}},required:["field","sort"],additionalProperties:!1}},"Most significant first",r)}case"grouping":{const o=t.filter(k);return o.length===0?null:M({type:"array",items:U(o),uniqueItems:!0},"Outermost first",r)}case"aggregation":{const o={};for(const i of t){const s=j(i);s.length>0&&(o[i.field]=M({enum:s},N(i),r))}return Object.keys(o).length===0?null:{type:"object",properties:o,additionalProperties:!1}}case"pivot":{const o=t.filter(k),i=t.map(l=>({col:l,fns:j(l,R)})).filter(l=>l.fns.length>0).map(({col:l,fns:a})=>M({type:"object",properties:{field:{const:l.field},aggFn:{enum:a}},required:["field","aggFn"],additionalProperties:!1},N(l),r));if(o.length===0||i.length===0)return null;const s={type:"array",items:U(o),uniqueItems:!0};return{type:"object",properties:{rowFields:s,columnFields:s,valueFields:{type:"array",items:{oneOf:i}}},required:["rowFields","columnFields","valueFields"],additionalProperties:!1}}case"columnVisibility":{const o={};for(const i of t.filter(oe))o[i.field]=M({type:"boolean"},N(i),r);return Object.keys(o).length===0?null:M({type:"object",properties:o,additionalProperties:!1},"false hides a column",r)}}}function z(e,t={}){const r={descriptions:t.descriptions!==!1,examples:t.examples!==!1},n=J(e),o={},i={};for(const l of ee(t)){const a=ke(l,n,r,o);a&&(i[I[l]]=a)}const s={$schema:"https://json-schema.org/draft/2020-12/schema",schemaVersion:1,title:Oe,type:"object",properties:i,additionalProperties:!1};return r.descriptions&&(s.description="Grid state to apply. Include only the parts the user asked to change."),Object.keys(o).length>0&&(s.$defs=o),s}const Ne=Symbol.for("opengridx.ai.validated");function _(e){return Object.defineProperty(e,Ne,{value:!0,enumerable:!1}),e}const O={ok:!1},$=e=>({ok:!0,value:e}),Ge=/^\d+(?:\.\d*)?(?:e[+-]?\d+)?$/i,Ve=/^\.\d+(?:e[+-]?\d+)?$/i,qe=/^\d{1,3}(?:,\d{3})+(?:\.\d*)?$/,_e=/[\p{Sc}\s]/gu;function Pe(e){let t=e.replace(_e,"");if(t==="")return e.trim()===""?$(null):O;let r=!1;t.startsWith("(")&&t.endsWith(")")&&(r=!0,t=t.slice(1,-1)),(t.startsWith("-")||t.startsWith("+")||t.startsWith("\u2212"))&&(t[0]!=="+"&&(r=!r),t=t.slice(1));let n=!1;if(t.endsWith("%")&&(n=!0,t=t.slice(0,-1)),qe.test(t))t=t.split(",").join("");else if(!Ge.test(t)&&!Ve.test(t))return O;let o=Number(t);return Number.isFinite(o)?(n&&(o/=100),r&&(o=-o),$(o)):O}function Ce(e,t){const r=e.trim();if(r==="")return $(null);const n=Q(r);return n?$(n):O}const De=new Set(["true","yes","1"]),Te=new Set(["false","no","0"]);function We(e,t){const r=e.trim().toLowerCase();return r===""?$(null):De.has(r)?$(!0):Te.has(r)?$(!1):O}function Re(e,t){const r=e.trim();if(r==="")return $(null);if(!t||t.length===0)return O;const n=r.toLowerCase();for(const o of t){const i=typeof o=="object"?o.value:o;if(String(i).toLowerCase()===n)return $(i)}for(const o of t)if(typeof o=="object"&&o.label.toLowerCase()===n)return $(o.value);return O}const p=e=>({ok:!0,value:e}),w={ok:!1,reason:"invalidValue"},P=e=>e.ok?p(e.value):w;function C(e){return e==null||typeof e=="string"&&e.trim()===""}function Le(e){return e==null?p(""):typeof e=="string"?p(e):typeof e=="number"||typeof e=="boolean"?p(String(e)):w}function Ie(e){return C(e)?p(null):typeof e=="number"?Number.isFinite(e)?p(e):w:typeof e!="string"?w:P(Pe(e))}function Je(e){return C(e)?p(null):e instanceof Date?Number.isNaN(e.getTime())?w:p(e):typeof e=="number"?Number.isFinite(e)?p(new Date(e)):w:typeof e!="string"?w:P(Ce(e))}function ie(e){return C(e)?p(null):typeof e=="boolean"?p(e):typeof e!="string"&&typeof e!="number"?w:P(We(String(e)))}function Ue(e,t){if(C(e))return p(null);if(typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return w;const r=t.valueOptions;return!r||r.length===0?p(e):P(Re(String(e),r))}function ze(e,t){switch(t.type){case"number":return Ie(e);case"date":return Je(e);case"boolean":return ie(e);case"singleSelect":return Ue(e,t);default:return Le(e)}}const B=200,Be=100;function u(e,t,r){return e.errors.length<Be&&e.errors.push({path:t,message:r}),null}function f(e){return typeof e=="string"?JSON.stringify(e.slice(0,60)):e===null||typeof e!="object"?String(e):Array.isArray(e)?"a list":"an object"}function se(e){return typeof e=="string"?e.trim().toLowerCase():null}function X(e){return Object.keys(e).filter(t=>t!=="__proto__")}function S(e,t,r,n,o){const i=typeof t=="string"?e.byField.get(t):void 0;return i?n(i)?i:u(e,r,`Field ${f(t)} cannot be ${o}`):u(e,r,`Unknown field ${f(t)}`)}function x(e,t,r){if(t==null)return[];const n=Array.isArray(t)?t:[t];return n.length>B&&u(e,r,`Only the first ${B} entries are read`),n.slice(0,B)}function G(e,t,r,n){const o=se(t);return n.find(i=>i.toLowerCase()===o)??u(e,r,`${f(t)} is not one of ${n.join(", ")}`)}function le(e,t,r,n){const o=ze(t,r);if(!o.ok)return u(e,n,`${f(t)} is not a valid ${r.type??"string"} value`);const i=o.value instanceof Date?ve(o.value):o.value;return i==null||i===""?u(e,n,"Missing value"):{v:i}}function Xe(e,t,r){const n=S(e,t.field,`${r}.field`,re,"filtered");if(!n)return null;const o=G(e,t.operator,`${r}.operator`,te(n));if(o===null)return null;const i={field:n.field,operator:o};if(Z.includes(i.operator))return i;const s=v(t,"value")?t.value:void 0;if(i.operator==="isAnyOf"){const a=[];return x(e,s,`${r}.value`).forEach((c,A)=>{const g=le(e,c,n,`${r}.value[${A}]`);g&&!a.includes(g.v)&&a.push(g.v)}),a.length===0?u(e,`${r}.value`,"No valid values"):(i.value=a,i)}if(Array.isArray(s))return u(e,`${r}.value`,"Expected one value, not a list");const l=le(e,s,n,`${r}.value`);return l?(i.value=l.v,i):null}function ae(e,t,r){return t===void 0?null:G(e,t,r,["and","or"])}function ue(e,t,r,n){const o=[];return x(e,t,r).forEach((i,s)=>{const l=`${r}[${s}]`;if(!b(i))u(e,l,`Expected a filter, got ${f(i)}`);else if(v(i,"items")||v(i,"logicOperator")){if(n>=q){u(e,l,`Groups nest at most ${q} levels`);return}const a=ue(e,i.items,`${l}.items`,n+1);a.length===0?u(e,l,"Empty group removed"):o.push({logicOperator:ae(e,i.logicOperator,`${l}.logicOperator`)??"and",items:a})}else{const a=Xe(e,i,l);a&&o.push(a)}}),o}function He(e,t,r){const n={};v(t,"items")&&(n.items=ue(e,t.items,`${r}.items`,0));const o=ae(e,t.logicOperator,`${r}.logicOperator`);return o&&(n.logicOperator=o),v(t,"quickFilterValues")&&(n.quickFilterValues=[],x(e,t.quickFilterValues,`${r}.quickFilterValues`).forEach((i,s)=>{const l=typeof i=="string"||typeof i=="number"?String(i).trim():null;l===null?u(e,`${r}.quickFilterValues[${s}]`,`Expected text, got ${f(i)}`):l!==""&&n.quickFilterValues?.push(l)})),n}function Ye(e,t,r){const n=[];return x(e,t,r).forEach((o,i)=>{const s=`${r}[${i}]`;if(!b(o))return u(e,s,`Expected { field, sort }, got ${f(o)}`);const l=S(e,o.field,`${s}.field`,ne,"sorted"),a=l&&G(e,o.sort,`${s}.sort`,["asc","desc"]);!l||!a||(n.some(c=>c.field===l.field)?u(e,s,`${f(l.field)} is sorted twice`):n.push({field:l.field,sort:a}))}),n}function H(e,t,r,n,o){const i=[];return x(e,t,r).forEach((s,l)=>{const a=S(e,s,`${r}[${l}]`,n,o);a&&!i.includes(a.field)&&i.push(a.field)}),i}const Ke=e=>j(e).length>0,Qe=e=>j(e,R).length>0;function Ze(e,t,r){const n={};for(const o of X(t)){if(se(t[o])==="none")continue;const i=S(e,o,`${r}.${o}`,Ke,"aggregated"),s=i&&G(e,t[o],`${r}.${o}`,j(i));i&&s&&(n[i.field]=s)}return n}function et(e,t,r){const n=[];return x(e,t.valueFields,`${r}.valueFields`).forEach((o,i)=>{const s=`${r}.valueFields[${i}]`;if(!b(o))return u(e,s,`Expected { field, aggFn }, got ${f(o)}`);const l=S(e,o.field,`${s}.field`,Qe,"a pivot value"),a=l&&G(e,o.aggFn,`${s}.aggFn`,j(l,R));l&&a&&!n.some(c=>c.field===l.field&&c.aggFn===a)&&n.push({field:l.field,aggFn:a})}),{rowFields:H(e,t.rowFields,`${r}.rowFields`,k,"a pivot label"),columnFields:H(e,t.columnFields,`${r}.columnFields`,k,"a pivot label"),valueFields:n}}function tt(e,t,r){const n={};for(const o of X(t)){const i=S(e,o,`${r}.${o}`,oe,"hidden"),s=ie(t[o]);i&&(s.ok&&s.value!==null?n[i.field]=s.value:u(e,`${r}.${o}`,`Expected true or false, got ${f(t[o])}`))}return n}function rt(e,t,r,n,o){t==="sort"?o.sortModel=Ye(e,r,n):t==="grouping"?o.rowGroupingModel=H(e,r,n,k,"grouped"):b(r)?t==="filter"?o.filterModel=He(e,r,n):t==="aggregation"?o.aggregationModel=Ze(e,r,n):t==="pivot"?o.pivotModel=et(e,r,n):o.columnVisibilityModel=tt(e,r,n):u(e,n,`Expected an object, got ${f(r)}`)}function Y(e,t,r={}){const n=nt(e,t,r);return _(n.state),_(n)}function nt(e,t,r){const n={errors:[],byField:new Map},o={};try{for(const l of J(t))n.byField.set(l.field,l);let i=e;if(typeof e=="string")try{i=JSON.parse(e)}catch{return u(n,"","Not valid JSON"),{state:o,errors:n.errors}}if(!b(i))return u(n,"",`Expected an object, got ${f(i)}`),{state:o,errors:n.errors};const s=ee(r);for(const l of X(i)){const a=L.find(c=>I[c]===l);l==="schemaVersion"?i[l]!==1&&u(n,l,`Unsupported schemaVersion ${f(i[l])}`):l==="message"?typeof i[l]!="string"&&u(n,l,`Expected text, got ${f(i[l])}`):a?s.includes(a)?rt(n,a,i[l],l,o):u(n,l,"Part not allowed"):u(n,l,"Unknown part")}}catch{return u(n,"","Could not read the input"),{state:{},errors:n.errors}}return{state:o,errors:n.errors}}const V="```";function D(){return typeof DOMException=="function"?new DOMException("The operation was aborted.","AbortError"):Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function ot(e){const t=e.trim();if(t.startsWith("{"))return{json:t,message:""};const r=e.indexOf(V),n=r<0?-1:e.indexOf(`
|
|
2
|
+
`,r+V.length),o=n<0?-1:e.indexOf(V,n+1),i=o<0?"":e.slice(r+V.length,n).trim().toLowerCase();return o<0||i!==""&&i!=="json"?{json:null,message:t}:{json:e.slice(n+1,o),message:`${e.slice(0,r)}${e.slice(o+V.length)}`.trim()}}function it(e){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:"Unknown error"}function ce(e,t){const r={state:_({}),errors:e};return t&&(r.message=t),_(r)}function st(e,t,r){let n=e,o="";if(typeof e=="string"){const a=ot(e);if(a.json===null)return ce([],a.message||void 0);o=a.message;try{n=JSON.parse(a.json)}catch{n=a.json}}const i=b(n)&&v(n,"message")&&typeof n.message=="string"?n.message.trim():"",s=[o,i].filter(Boolean).join(`
|
|
3
3
|
|
|
4
|
-
`),l=
|
|
4
|
+
`),l=Y(n,t,r);return s&&(l.message=s),l}function lt(e){const{columns:t,callModel:r,parts:n,schemaOptions:o={}}=e,i={include:n??o.include,exclude:o.exclude},s=z(t,{...o,...i});return async(l,a)=>{const c=a?.signal??new AbortController().signal;if(c.aborted)throw D();const A=new Promise((m,y)=>{c.addEventListener("abort",()=>y(D()),{once:!0})});A.catch(()=>{});let g;try{const m={prompt:String(l),schema:s,currentState:a?.currentState??{},history:Array.isArray(a?.history)?a.history:[]};g=await Promise.race([r(m,{signal:c}),A])}catch(m){if(c.aborted)throw D();return ce([{path:"",message:`The model call failed: ${it(m)}`}])}if(c.aborted)throw D();return st(g,t,i)}}const at=20,ut=1e3,ct=[{name:"set_filter",part:"filter",description:"Replace the filter model of the grid (filters and quick-filter words)."},{name:"set_sort",part:"sort",description:"Replace the sort model of the grid, most significant field first. An empty list clears sorting."},{name:"set_grouping",part:"grouping",description:"Group the rows by these fields, outermost first. An empty list removes grouping."},{name:"set_aggregation",part:"aggregation",description:"Replace the summaries: field to aggregation function. An empty object removes them."},{name:"set_column_visibility",part:"columnVisibility",description:"Show (true) or hide (false) columns. Columns not listed keep their visibility."}];function E(e,t=""){return{ok:!1,errors:[{path:t,message:e}]}}async function T(e){try{return e()}catch(t){return E(t instanceof Error&&t.message?t.message:"The tool failed")}}function W(e){const t=e?.current;return t&&typeof t.getGridAiState=="function"?t:null}function ft(e){return e instanceof Date?Number.isNaN(e.getTime())?null:e.toISOString():typeof e=="number"?Number.isFinite(e)?e:null:typeof e=="string"||typeof e=="boolean"?e:null}function dt(e,t,r,n,o){const i=I[n],s=z(t,{include:[n]});if(!v(s.properties,i))return null;const{$schema:l,schemaVersion:a,title:c,description:A,...g}=s;return{name:r,description:o,inputSchema:{...g,required:[i]},execute:m=>T(()=>{const y=W(e);if(!y)return E("The grid is not ready");if(!b(m)||!v(m,i))return E(`Expected an object with "${i}"`,i);const{state:d,errors:F}=Y({[i]:m[i]},t,{include:[n]});if(F.length>0)return{ok:!1,errors:F};const h={};return d.filterModel&&y.setFilterModel(h.filterModel=d.filterModel),d.sortModel&&y.setSortModel(h.sortModel=d.sortModel),d.rowGroupingModel&&y.setRowGroupingModel(h.rowGroupingModel=d.rowGroupingModel),d.aggregationModel&&y.setAggregationModel(h.aggregationModel=d.aggregationModel),d.columnVisibilityModel&&(h.columnVisibilityModel={...y.getGridAiState().columnVisibilityModel,...d.columnVisibilityModel},y.setColumnVisibilityModel(h.columnVisibilityModel)),{ok:!0,applied:h}})}}const fe={type:"object",properties:{},additionalProperties:!1};function pt(e,t,r={}){const n=J(t),o=[{name:"get_grid_state",description:"Read the current filter, sort, grouping, aggregation, pivot and column visibility of the grid, and its columns.",inputSchema:fe,execute:()=>T(()=>{const i=W(e);return i?{ok:!0,state:i.getGridAiState(),columns:n.map(s=>({field:s.field,headerName:typeof s.headerName=="string"?s.headerName:s.field,type:typeof s.type=="string"?s.type:"string"}))}:E("The grid is not ready")})}];for(const{name:i,part:s,description:l}of ct){const a=dt(e,n,i,s,l);a&&o.push(a)}if(o.push({name:"clear_filters",description:"Remove every filter and the quick-filter words.",inputSchema:fe,execute:()=>T(()=>{const i=W(e);if(!i)return E("The grid is not ready");const s={items:[]};return i.setFilterModel(s),{ok:!0,applied:{filterModel:s}}})}),r.allowRowAccess===!0){const i=typeof r.maxRows=="number"&&r.maxRows>=1?Math.min(Math.floor(r.maxRows),ut):at,s=Array.isArray(r.fields)?n.filter(l=>r.fields?.includes(l.field)):n;o.push({name:"get_row_summary",description:`Count the rows that pass the current filter and read the first ones (at most ${i}, fields: ${s.map(l=>l.field).join(", ")}).`,inputSchema:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:i}},additionalProperties:!1},execute:l=>T(()=>{const a=W(e);if(!a)return E("The grid is not ready");const c=b(l)&&v(l,"limit")?l.limit:i,A=typeof c=="number"&&c>=1?Math.min(Math.floor(c),i):i,g=a.getAllFilteredRows(),m=Array.isArray(g)?g:[],y=m.slice(0,A).map(d=>{const F={};if(!b(d))return F;for(const h of s)F[h.field]=ft(ge(d,h.field,h));return F});return{ok:!0,rowCount:m.length,rows:y}})})}return o}export{pt as createGridAgentTools,lt as createGridAiPromptHandler,z as getGridAiSchema,Y as validateGridAiState};
|