@opencorestack/opengridx 3.5.1 → 3.7.0

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.
Files changed (114) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +2 -0
  3. package/dist/ai.cjs +4 -2
  4. package/dist/ai.cjs.map +1 -1
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.es.js +4 -2
  7. package/dist/ai.es.js.map +1 -1
  8. package/dist/index.d.ts +62 -0
  9. package/dist/opengridx.css +1 -1
  10. package/dist/opengridx.es.js +9643 -9024
  11. package/dist/opengridx.es.js.map +1 -1
  12. package/dist/opengridx.umd.js +16 -16
  13. package/dist/opengridx.umd.js.map +1 -1
  14. package/docs/API_REFERENCE.md +17 -3
  15. package/docs/README.md +2 -0
  16. package/docs/architecture/datagrid-orchestration.md +46 -29
  17. package/docs/architecture/grid-row-meta.md +1 -1
  18. package/docs/customization/slots-api.md +1 -1
  19. package/docs/customization/theming.md +43 -0
  20. package/docs/features/ai-toolkit.md +2 -2
  21. package/docs/features/export-guide.md +2 -0
  22. package/docs/features/header-filters.md +34 -0
  23. package/docs/features/keyboard-navigation.md +2 -0
  24. package/docs/features/nextjs.md +241 -0
  25. package/docs/features/pdf-export.md +2 -0
  26. package/docs/features/pinning.md +2 -0
  27. package/docs/features/rtl.md +58 -0
  28. package/docs/features/virtualization.md +16 -2
  29. package/docs/performance.md +89 -119
  30. package/docs/roadmap.md +4 -2
  31. package/lib/ai/promptHandler.ts +12 -8
  32. package/lib/ai/validate.ts +5 -2
  33. package/lib/components/AiAssistant/GridAiAssistantPanel.css +4 -2
  34. package/lib/components/Cell/Cell.css +31 -9
  35. package/lib/components/Cell/Cell.tsx +2 -2
  36. package/lib/components/ColumnGroupHeader/ColumnGroupHeader.css +4 -4
  37. package/lib/components/ColumnResizeHandle/ColumnResizeHandle.css +3 -3
  38. package/lib/components/ColumnResizeHandle/ColumnResizeHandle.tsx +18 -2
  39. package/lib/components/ColumnVisibilityPanel/ColumnVisibilityPanel.css +3 -1
  40. package/lib/components/DataGrid/DataGrid.css +19 -13
  41. package/lib/components/DataGrid/DataGrid.tsx +163 -670
  42. package/lib/components/DataGrid/GridAggregationFooter.tsx +3 -3
  43. package/lib/components/DataGrid/GridListView.tsx +3 -1
  44. package/lib/components/DataGrid/GridRoot.tsx +239 -0
  45. package/lib/components/DataGrid/GridViewport.tsx +314 -0
  46. package/lib/components/FilterPanel/FilterPanel.css +9 -8
  47. package/lib/components/Header/ColumnMenu.css +5 -4
  48. package/lib/components/Header/ColumnMenu.tsx +14 -6
  49. package/lib/components/Header/Header.css +23 -14
  50. package/lib/components/Header/Header.tsx +16 -9
  51. package/lib/components/Header/headerColumnStyle.ts +3 -2
  52. package/lib/components/HeaderFilter/HeaderFilter.css +9 -3
  53. package/lib/components/HeaderFilter/HeaderFilterCell.tsx +21 -18
  54. package/lib/components/HeaderFilter/HeaderFilterOperatorMenu.tsx +5 -4
  55. package/lib/components/HeaderFilter/HeaderFilterRow.tsx +9 -3
  56. package/lib/components/ListView/ListViewRow.tsx +1 -1
  57. package/lib/components/Pagination/Pagination.css +5 -1
  58. package/lib/components/Pagination/Pagination.tsx +4 -4
  59. package/lib/components/Row/Row.css +2 -2
  60. package/lib/components/Row/Row.tsx +3 -3
  61. package/lib/components/SkeletonRow/SkeletonRow.tsx +2 -2
  62. package/lib/components/Toolbar/GridToolbar.css +8 -7
  63. package/lib/components/Toolbar/GridToolbar.tsx +8 -28
  64. package/lib/components/Toolbar/PivotPanel.css +3 -3
  65. package/lib/components/Toolbar/PivotPanel.tsx +4 -7
  66. package/lib/components/ui/ExpandIcon.css +13 -0
  67. package/lib/components/ui/ExpandIcon.tsx +2 -4
  68. package/lib/hooks/core/useGridCellSelection.ts +20 -5
  69. package/lib/hooks/core/useGridColumns.tsx +2 -2
  70. package/lib/hooks/core/useGridDevWarnings.ts +3 -1
  71. package/lib/hooks/core/useGridEditPipeline.ts +55 -0
  72. package/lib/hooks/core/useGridKeyboardNavigation.ts +7 -4
  73. package/lib/hooks/core/useGridRangeEditing.ts +129 -0
  74. package/lib/hooks/core/useGridRenderWindow.ts +66 -0
  75. package/lib/hooks/core/useGridScrollSync.ts +28 -5
  76. package/lib/hooks/core/useGridScrollViewport.ts +42 -0
  77. package/lib/hooks/core/useGridSelectionAndStateApi.ts +61 -0
  78. package/lib/hooks/core/useGridToolbarStack.ts +49 -0
  79. package/lib/hooks/core/useGridViewApis.ts +46 -0
  80. package/lib/hooks/core/useLayout.ts +13 -6
  81. package/lib/hooks/useRowGrouping.ts +9 -9
  82. package/lib/styles/base/variables.css +12 -0
  83. package/lib/theme/DataGridThemeProvider.tsx +15 -0
  84. package/lib/theme/__baseline__/default-theme.darwin.chromium.json +1503 -0
  85. package/lib/theme/__baseline__/default-theme.darwin.firefox.json +1503 -0
  86. package/lib/theme/__baseline__/default-theme.darwin.webkit.json +1503 -0
  87. package/lib/theme/types.ts +31 -0
  88. package/lib/types/ai.ts +109 -0
  89. package/lib/types/api.ts +169 -0
  90. package/lib/types/columns.ts +341 -0
  91. package/lib/types/dataSource.ts +40 -0
  92. package/lib/types/editing.ts +77 -0
  93. package/lib/types/export.ts +164 -0
  94. package/lib/types/filtering.ts +52 -0
  95. package/lib/types/grouping.ts +27 -0
  96. package/lib/types/index.ts +18 -1672
  97. package/lib/types/locale.ts +51 -0
  98. package/lib/types/props.ts +405 -0
  99. package/lib/types/rows.ts +132 -0
  100. package/lib/types/selection.ts +66 -0
  101. package/lib/types/slots.ts +56 -0
  102. package/lib/types/sorting.ts +25 -0
  103. package/lib/types/state.ts +35 -0
  104. package/lib/utils/aggregation/index.ts +56 -1
  105. package/lib/utils/direction.ts +52 -0
  106. package/lib/utils/export/exportToExcelAdvanced.ts +9 -2
  107. package/lib/utils/export/exportToPdf.ts +2 -1
  108. package/lib/utils/filtering/index.ts +58 -6
  109. package/lib/utils/headerFilterLocale.ts +37 -0
  110. package/lib/utils/scroll/index.ts +5 -3
  111. package/lib/utils/sorting/index.ts +141 -26
  112. package/lib/utils/values.ts +10 -6
  113. package/llms.txt +4 -2
  114. package/package.json +4 -2
package/dist/ai.es.js CHANGED
@@ -1,2 +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 o=e[t];if(!r?.valueGetter)return{value:o};try{return{value:r.valueGetter({row:e,field:t,value:o})}}catch(n){return{value:void 0,error:n??new Error("valueGetter failed")}}}function ge(e,t,r){const{value:o,error:n}=pe(e,t,r);return n!==void 0&&de(`valueGetter:${t}`,`valueGetter for column "${t}" threw; the value is read as undefined`,n),o}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 o=me.exec(r);if(o){const n=Number(o[1]),i=Number(o[2])-1,s=Number(o[3]);if(t=new Date(n,i,s),t.getMonth()!==i||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"),o=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${r}-${o}-${n}`}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(o=>t.includes(o)&&!r.includes(o))}function U(e){if(!Array.isArray(e))return[];const t=new Set,r=[];for(const o of e){if(!b(o))continue;const n=o.field;typeof n!="string"||n===""||n.startsWith("__")||o.isSpacer===!0||t.has(n)||(t.add(n),r.push(o))}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,oe=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(n=>n==="count"),o=e.availableAggregationFunctions;return Array.isArray(o)?r.filter(n=>o.includes(n)):[...r]}function $e(e){const t=[];if(!Array.isArray(e.valueOptions))return t;for(const r of e.valueOptions){const o=r!==null&&typeof r=="object"?r.value:r;(typeof o=="string"||typeof o=="number"&&Number.isFinite(o))&&!t.includes(o)&&t.push(o)}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 n=$e(e),i=n.length>0?{enum:n}:{type:"string"};r={anyOf:[i,{type:"array",items:i}]};break}default:r={type:"string"}}const o=Me(e,t);return o.length>0?{...r,examples:o}:r}function Oe(e,t){const r=te(e),o=r.filter(s=>Z.includes(s)),n=e.type==="singleSelect"?"; isAnyOf takes an array":"",i=o.length>0?`${o.join(" and ")} take no value${n}`:n.slice(2);return M({type:"object",properties:{field:{const:e.field},operator:{enum:r},value:Ae(e,t)},required:["field","operator"],additionalProperties:!1},i?`${N(e)}: ${i}`:N(e),t)}function Fe(e,t,r){const o=e.filter(re),n={},i={enum:["and","or"]};if(o.length>0){r.filterItem={oneOf:o.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:i,items:{type:"array",items:l}},required:["logicOperator","items"],additionalProperties:!1}}n.items={type:"array",items:{anyOf:[{$ref:"#/$defs/filterItem"},{$ref:"#/$defs/filterGroup1"}]}},n.logicOperator=i}return n.quickFilterValues=M({type:"array",items:{type:"string"}},"Words a row must contain, in any column",t),{type:"object",properties:n,additionalProperties:!1}}function J(e){return{enum:e.map(t=>t.field)}}function Se(e,t,r,o){switch(e){case"filter":return Fe(t,r,o);case"sort":{const n=t.filter(ne);return n.length===0?null:M({type:"array",items:{type:"object",properties:{field:J(n),sort:{enum:["asc","desc"]}},required:["field","sort"],additionalProperties:!1}},"Most significant first",r)}case"grouping":{const n=t.filter(k);return n.length===0?null:M({type:"array",items:J(n),uniqueItems:!0},"Outermost first",r)}case"aggregation":{const n={};for(const i of t){const s=S(i);s.length>0&&(n[i.field]=M({enum:s},N(i),r))}return Object.keys(n).length===0?null:{type:"object",properties:n,additionalProperties:!1}}case"pivot":{const n=t.filter(k),i=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(n.length===0||i.length===0)return null;const s={type:"array",items:J(n),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 n={};for(const i of t.filter(oe))n[i.field]=M({type:"boolean"},N(i),r);return Object.keys(n).length===0?null:M({type:"object",properties:n,additionalProperties:!1},"false hides a column",r)}}}function X(e,t={}){const r={descriptions:t.descriptions!==!1,examples:t.examples!==!1},o=U(e),n={},i={};for(const l of ee(t)){const a=Se(l,o,r,n);a&&(i[L[l]]=a)}const s={$schema:"https://json-schema.org/draft/2020-12/schema",schemaVersion:1,title:ve,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(n).length>0&&(s.$defs=n),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 o=!1;if(t.endsWith("%")&&(o=!0,t=t.slice(0,-1)),ke.test(t))t=t.split(",").join("");else if(!xe.test(t)&&!Ee.test(t))return O;let n=Number(t);return Number.isFinite(n)?(o&&(n/=100),r&&(n=-n),$(n)):O}function Ve(e,t){const r=e.trim();if(r==="")return $(null);const o=Q(r);return o?$(o):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 o=r.toLowerCase();for(const n of t){const i=typeof n=="object"?n.value:n;if(String(i).toLowerCase()===o)return $(i)}for(const n of t)if(typeof n=="object"&&n.label.toLowerCase()===o)return $(n.value);return O}const d=e=>({ok:!0,value:e}),w={ok:!1,reason:"invalidValue"},P=e=>e.ok?d(e.value):w;function C(e){return e==null||typeof e=="string"&&e.trim()===""}function De(e){return e==null?d(""):typeof e=="string"?d(e):typeof e=="number"||typeof e=="boolean"?d(String(e)):w}function Te(e){return C(e)?d(null):typeof e=="number"?Number.isFinite(e)?d(e):w:typeof e!="string"?w:P(Ge(e))}function Re(e){return C(e)?d(null):e instanceof Date?Number.isNaN(e.getTime())?w:d(e):typeof e=="number"?Number.isFinite(e)?d(new Date(e)):w:typeof e!="string"?w:P(Ve(e))}function ie(e){return C(e)?d(null):typeof e=="boolean"?d(e):typeof e!="string"&&typeof e!="number"?w:P(Pe(String(e)))}function We(e,t){if(C(e))return d(null);if(typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return w;const r=t.valueOptions;return!r||r.length===0?d(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 ie(e);case"singleSelect":return We(e,t);default:return De(e)}}const B=200,Le=100;function u(e,t,r){return e.errors.length<Le&&e.errors.push({path:t,message:r}),null}function p(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,o,n){const i=typeof t=="string"?e.byField.get(t):void 0;return i?o(i)?i:u(e,r,`Field ${p(t)} cannot be ${n}`):u(e,r,`Unknown field ${p(t)}`)}function x(e,t,r){if(t==null)return[];const o=Array.isArray(t)?t:[t];return o.length>B&&u(e,r,`Only the first ${B} entries are read`),o.slice(0,B)}function G(e,t,r,o){const n=se(t);return o.find(i=>i.toLowerCase()===n)??u(e,r,`${p(t)} is not one of ${o.join(", ")}`)}function le(e,t,r,o){const n=Ie(t,r);if(!n.ok)return u(e,o,`${p(t)} is not a valid ${r.type??"string"} value`);const i=n.value instanceof Date?ye(n.value):n.value;return i==null||i===""?u(e,o,"Missing value"):{v:i}}function Ue(e,t,r){const o=j(e,t.field,`${r}.field`,re,"filtered");if(!o)return null;const n=G(e,t.operator,`${r}.operator`,te(o));if(n===null)return null;const i={field:o.field,operator:n};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,o,`${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,o,`${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,o){const n=[];return x(e,t,r).forEach((i,s)=>{const l=`${r}[${s}]`;if(!b(i))u(e,l,`Expected a filter, got ${p(i)}`);else if(v(i,"items")||v(i,"logicOperator")){if(o>=q){u(e,l,`Groups nest at most ${q} levels`);return}const a=ue(e,i.items,`${l}.items`,o+1);a.length===0?u(e,l,"Empty group removed"):n.push({logicOperator:ae(e,i.logicOperator,`${l}.logicOperator`)??"and",items:a})}else{const a=Ue(e,i,l);a&&n.push(a)}}),n}function Je(e,t,r){const o={};v(t,"items")&&(o.items=ue(e,t.items,`${r}.items`,0));const n=ae(e,t.logicOperator,`${r}.logicOperator`);return n&&(o.logicOperator=n),v(t,"quickFilterValues")&&(o.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 ${p(i)}`):l!==""&&o.quickFilterValues?.push(l)})),o}function Xe(e,t,r){const o=[];return x(e,t,r).forEach((n,i)=>{const s=`${r}[${i}]`;if(!b(n))return u(e,s,`Expected { field, sort }, got ${p(n)}`);const l=j(e,n.field,`${s}.field`,ne,"sorted"),a=l&&G(e,n.sort,`${s}.sort`,["asc","desc"]);!l||!a||(o.some(c=>c.field===l.field)?u(e,s,`${p(l.field)} is sorted twice`):o.push({field:l.field,sort:a}))}),o}function Y(e,t,r,o,n){const i=[];return x(e,t,r).forEach((s,l)=>{const a=j(e,s,`${r}[${l}]`,o,n);a&&!i.includes(a.field)&&i.push(a.field)}),i}const Be=e=>S(e).length>0,He=e=>S(e,W).length>0;function Ye(e,t,r){const o={};for(const n of H(t)){if(se(t[n])==="none")continue;const i=j(e,n,`${r}.${n}`,Be,"aggregated"),s=i&&G(e,t[n],`${r}.${n}`,S(i));i&&s&&(o[i.field]=s)}return o}function ze(e,t,r){const o=[];return x(e,t.valueFields,`${r}.valueFields`).forEach((n,i)=>{const s=`${r}.valueFields[${i}]`;if(!b(n))return u(e,s,`Expected { field, aggFn }, got ${p(n)}`);const l=j(e,n.field,`${s}.field`,He,"a pivot value"),a=l&&G(e,n.aggFn,`${s}.aggFn`,S(l,W));l&&a&&!o.some(c=>c.field===l.field&&c.aggFn===a)&&o.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:o}}function Ke(e,t,r){const o={};for(const n of H(t)){const i=j(e,n,`${r}.${n}`,oe,"hidden"),s=ie(t[n]);i&&(s.ok&&s.value!==null?o[i.field]=s.value:u(e,`${r}.${n}`,`Expected true or false, got ${p(t[n])}`))}return o}function Qe(e,t,r,o,n){t==="sort"?n.sortModel=Xe(e,r,o):t==="grouping"?n.rowGroupingModel=Y(e,r,o,k,"grouped"):b(r)?t==="filter"?n.filterModel=Je(e,r,o):t==="aggregation"?n.aggregationModel=Ye(e,r,o):t==="pivot"?n.pivotModel=ze(e,r,o):n.columnVisibilityModel=Ke(e,r,o):u(e,o,`Expected an object, got ${p(r)}`)}function z(e,t,r={}){const o=Ze(e,t,r);return _(o.state),_(o)}function Ze(e,t,r){const o={errors:[],byField:new Map},n={};try{for(const l of U(t))o.byField.set(l.field,l);let i=e;if(typeof e=="string")try{i=JSON.parse(e)}catch{return u(o,"","Not valid JSON"),{state:n,errors:o.errors}}if(!b(i))return u(o,"",`Expected an object, got ${p(i)}`),{state:n,errors:o.errors};const s=ee(r);for(const l of H(i)){const a=I.find(c=>L[c]===l);l==="schemaVersion"?i[l]!==1&&u(o,l,`Unsupported schemaVersion ${p(i[l])}`):a?s.includes(a)?Qe(o,a,i[l],l,n):u(o,l,"Part not allowed"):u(o,l,"Unknown part")}}catch{return u(o,"","Could not read the input"),{state:{},errors:o.errors}}return{state:n,errors:o.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),o=r<0?-1:e.indexOf(`
2
- `,r+V.length),n=o<0?-1:e.indexOf(V,o+1),i=n<0?"":e.slice(r+V.length,o).trim().toLowerCase();return n<0||i!==""&&i!=="json"?{json:null,message:t}:{json:e.slice(o+1,n),message:`${e.slice(0,r)}${e.slice(n+V.length)}`.trim()}}function tt(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 rt(e,t,r){let o=e,n="";if(typeof e=="string"){const s=et(e);if(s.json===null)return ce([],s.message||void 0);o=s.json,n=s.message}else if(b(e)&&v(e,"message")&&typeof e.message=="string"){const{message:s,...l}=e;o=l,n=s}const i=z(o,t,r);return n&&(i.message=n),i}function nt(e){const{columns:t,callModel:r,parts:o,schemaOptions:n={}}=e,i={include:o??n.include,exclude:n.exclude},s=X(t,{...n,...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: ${tt(m)}`}])}if(c.aborted)throw D();return rt(g,t,i)}}const ot=20,it=1e3,st=[{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 R(e){const t=e?.current;return t&&typeof t.getGridAiState=="function"?t:null}function lt(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 at(e,t,r,o,n){const i=L[o],s=X(t,{include:[o]});if(!v(s.properties,i))return null;const{$schema:l,schemaVersion:a,title:c,description:A,...g}=s;return{name:r,description:n,inputSchema:{...g,required:[i]},execute:m=>T(()=>{const y=R(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:f,errors:F}=z({[i]:m[i]},t,{include:[o]});if(F.length>0)return{ok:!1,errors:F};const h={};return f.filterModel&&y.setFilterModel(h.filterModel=f.filterModel),f.sortModel&&y.setSortModel(h.sortModel=f.sortModel),f.rowGroupingModel&&y.setRowGroupingModel(h.rowGroupingModel=f.rowGroupingModel),f.aggregationModel&&y.setAggregationModel(h.aggregationModel=f.aggregationModel),f.columnVisibilityModel&&(h.columnVisibilityModel={...y.getGridAiState().columnVisibilityModel,...f.columnVisibilityModel},y.setColumnVisibilityModel(h.columnVisibilityModel)),{ok:!0,applied:h}})}}const fe={type:"object",properties:{},additionalProperties:!1};function ut(e,t,r={}){const o=U(t),n=[{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=R(e);return i?{ok:!0,state:i.getGridAiState(),columns:o.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 st){const a=at(e,o,i,s,l);a&&n.push(a)}if(n.push({name:"clear_filters",description:"Remove every filter and the quick-filter words.",inputSchema:fe,execute:()=>T(()=>{const i=R(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),it):ot,s=Array.isArray(r.fields)?o.filter(l=>r.fields?.includes(l.field)):o;n.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=R(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(f=>{const F={};if(!b(f))return F;for(const h of s)F[h.field]=lt(ge(f,h.field,h));return F});return{ok:!0,rowCount:m.length,rows:y}})})}return n}export{ut as createGridAgentTools,nt as createGridAiPromptHandler,X as getGridAiSchema,z as validateGridAiState};
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),i=n<0?-1:e.indexOf(V,n+1),o=i<0?"":e.slice(r+V.length,n).trim().toLowerCase();return i<0||o!==""&&o!=="json"?{json:null,message:t}:{json:e.slice(n+1,i),message:`${e.slice(0,r)}${e.slice(i+V.length)}`.trim()}}function tt(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 rt(e,t,r){let n=e,i="";if(typeof e=="string"){const a=et(e);if(a.json===null)return ce([],a.message||void 0);i=a.message;try{n=JSON.parse(a.json)}catch{n=a.json}}const o=b(n)&&v(n,"message")&&typeof n.message=="string"?n.message.trim():"",s=[i,o].filter(Boolean).join(`
3
+
4
+ `),l=z(n,t,r);return s&&(l.message=s),l}function nt(e){const{columns:t,callModel:r,parts:n,schemaOptions:i={}}=e,o={include:n??i.include,exclude:i.exclude},s=B(t,{...i,...o});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: ${tt(m)}`}])}if(c.aborted)throw D();return rt(g,t,o)}}const it=20,ot=1e3,st=[{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 R(e){const t=e?.current;return t&&typeof t.getGridAiState=="function"?t:null}function lt(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 at(e,t,r,n,i){const o=L[n],s=B(t,{include:[n]});if(!v(s.properties,o))return null;const{$schema:l,schemaVersion:a,title:c,description:A,...g}=s;return{name:r,description:i,inputSchema:{...g,required:[o]},execute:m=>T(()=>{const y=R(e);if(!y)return E("The grid is not ready");if(!b(m)||!v(m,o))return E(`Expected an object with "${o}"`,o);const{state:d,errors:F}=z({[o]:m[o]},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 ut(e,t,r={}){const n=J(t),i=[{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 o=R(e);return o?{ok:!0,state:o.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:o,part:s,description:l}of st){const a=at(e,n,o,s,l);a&&i.push(a)}if(i.push({name:"clear_filters",description:"Remove every filter and the quick-filter words.",inputSchema:fe,execute:()=>T(()=>{const o=R(e);if(!o)return E("The grid is not ready");const s={items:[]};return o.setFilterModel(s),{ok:!0,applied:{filterModel:s}}})}),r.allowRowAccess===!0){const o=typeof r.maxRows=="number"&&r.maxRows>=1?Math.min(Math.floor(r.maxRows),ot):it,s=Array.isArray(r.fields)?n.filter(l=>r.fields?.includes(l.field)):n;i.push({name:"get_row_summary",description:`Count the rows that pass the current filter and read the first ones (at most ${o}, fields: ${s.map(l=>l.field).join(", ")}).`,inputSchema:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:o}},additionalProperties:!1},execute:l=>T(()=>{const a=R(e);if(!a)return E("The grid is not ready");const c=b(l)&&v(l,"limit")?l.limit:o,A=typeof c=="number"&&c>=1?Math.min(Math.floor(c),o):o,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]=lt(ge(d,h.field,h));return F});return{ok:!0,rowCount:m.length,rows:y}})})}return i}export{ut as createGridAgentTools,nt as createGridAiPromptHandler,B as getGridAiSchema,z as validateGridAiState};