@svgrid/grid 2.2.32 → 2.4.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.
- package/README.md +199 -199
- package/dist/DockNodeView.svelte +1 -1
- package/dist/FlexRender.svelte +96 -96
- package/dist/GridFooter.svelte +178 -179
- package/dist/GridMenus.svelte +705 -782
- package/dist/SvAutoComplete.svelte +165 -165
- package/dist/SvAvatar.svelte +75 -75
- package/dist/SvCalendar.svelte +503 -503
- package/dist/SvCarousel.svelte +141 -141
- package/dist/SvCheckBox.svelte +102 -102
- package/dist/SvCircularProgress.svelte +109 -109
- package/dist/SvColorInput.svelte +181 -181
- package/dist/SvComboBox.svelte +275 -275
- package/dist/SvContextMenu.svelte +116 -116
- package/dist/SvCountryInput.svelte +160 -160
- package/dist/SvDateRangeInput.svelte +1 -1
- package/dist/SvDrawer.svelte +254 -254
- package/dist/SvDropDownList.svelte +374 -374
- package/dist/SvDurationInput.svelte +126 -126
- package/dist/SvField.svelte +293 -293
- package/dist/SvForm.svelte +437 -437
- package/dist/SvGrid.css +2814 -2804
- package/dist/SvGrid.svelte +3490 -3513
- package/dist/SvGridChart.svelte +1716 -1724
- package/dist/SvGridChartPanel.svelte +485 -485
- package/dist/SvGridChartView.svelte +70 -70
- package/dist/SvGridDropdown.svelte +728 -728
- package/dist/SvGridSelect.svelte +266 -268
- package/dist/SvGroupCell.svelte +116 -116
- package/dist/SvKbd.svelte +1 -1
- package/dist/SvList.svelte +1 -1
- package/dist/SvListBox.svelte +326 -326
- package/dist/SvMaskedInput.svelte +122 -122
- package/dist/SvMenu.svelte +124 -124
- package/dist/SvMenuList.svelte +146 -146
- package/dist/SvMenubar.svelte +1 -1
- package/dist/SvMultiSelect.svelte +289 -290
- package/dist/SvNumberInput.svelte +168 -168
- package/dist/SvOtpInput.svelte +158 -158
- package/dist/SvPasswordInput.svelte +151 -151
- package/dist/SvPhoneInput.svelte +133 -133
- package/dist/SvPopover.svelte +197 -197
- package/dist/SvProgress.svelte +116 -116
- package/dist/SvRadioGroup.svelte +107 -107
- package/dist/SvRating.svelte +112 -112
- package/dist/SvResult.svelte +73 -73
- package/dist/SvRichText.svelte +211 -207
- package/dist/SvRowGroupPanel.svelte +170 -170
- package/dist/SvScrollArea.svelte +61 -61
- package/dist/SvSlider.svelte +200 -200
- package/dist/SvSwitchButton.svelte +108 -108
- package/dist/SvTagsInput.svelte +112 -112
- package/dist/SvTextInput.svelte +147 -147
- package/dist/SvTimePicker.svelte +245 -245
- package/dist/SvToaster.svelte +159 -159
- package/dist/SvToggleButton.svelte +85 -85
- package/dist/SvTooltip.svelte +161 -161
- package/dist/SvTour.svelte +208 -204
- package/dist/SvTree.svelte +444 -444
- package/dist/SvTreeSelect.svelte +235 -237
- package/dist/cdn/{GridMenus-C6ixSGWW.js → GridMenus-BpVcKyUr.js} +5 -7
- package/dist/cdn/{GridMenus-Cyk3qpJ7.js → GridMenus-CeXL5IW4.js} +153 -152
- package/dist/cdn/{SvDateTimePicker-ClqtVIj3.js → SvDateTimePicker-DSUhIta8.js} +165 -165
- package/dist/cdn/{SvDateTimePicker-CdqaP61H.js → SvDateTimePicker-h9kPyszT.js} +572 -555
- package/dist/cdn/{SvGridChart-BcLCYvw9.js → SvGridChart-Bs2GIR2Q.js} +28 -21
- package/dist/cdn/{SvGridChart-BhnFdLd0.js → SvGridChart-CwhFz7GV.js} +2 -2
- package/dist/cdn/{SvGridChartPanel-Cmx9DHAS.js → SvGridChartPanel-1WXuStzM.js} +2 -2
- package/dist/cdn/{SvGridChartPanel-DvjwxLvK.js → SvGridChartPanel-e5_nqNP9.js} +22 -14
- package/dist/cdn/{SvGridChartView-PwqI4s02.js → SvGridChartView-SmPW10dI.js} +3 -3
- package/dist/cdn/{SvGridChartView-B40DTJSX.js → SvGridChartView-eSPuJE6g.js} +2 -2
- package/dist/cdn/{SvGridDropdown-D0VdjeR8.js → SvGridDropdown-B1ZcLpgs.js} +1 -1
- package/dist/cdn/{SvGridDropdown-Dh-2ej8j.js → SvGridDropdown-CtdbHcIS.js} +6 -5
- package/dist/cdn/{chart-T1usDN0o.js → chart-i4XcXyHJ.js} +12 -10
- package/dist/cdn/disclose-version-Dr7rEVv-.js +2866 -0
- package/dist/cdn/{export-format-JT5pWVT8.js → export-format-Cv1Dll6k.js} +66 -245
- package/dist/cdn/{src-CgD-wiuS.js → src-DbeN1ReZ.js} +9223 -8944
- package/dist/cdn/{src-BgHjWF0Q.js → src-DmEQFW5_.js} +9023 -8828
- package/dist/cdn/svgrid.js +9 -9
- package/dist/cdn/svgrid.svelte-external.js +9 -9
- package/dist/chart-export.js +8 -8
- package/dist/chart.d.ts +2 -0
- package/dist/chart.js +1 -4
- package/dist/columns.js +9 -2
- package/dist/createMenu.svelte.js +0 -1
- package/dist/createPopoverSelect.svelte.d.ts +2 -2
- package/dist/editing.js +1 -1
- package/dist/export-format.js +3 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/_svelte_metadata.json +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/_metadata.json +178 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/attachments-qzRy9DX4.js +3843 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/attachments-qzRy9DX4.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/constants-RLNOXCpz.js +23 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/constants-RLNOXCpz.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/dev-DPd12uEU.js +1925 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/dev-DPd12uEU.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/events-CDC4DKuQ.js +206 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/events-CDC4DKuQ.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/flags-BD-lYX7s.js +20 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/flags-BD-lYX7s.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/hydration-D3UBU2t8.js +264 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/hydration-D3UBU2t8.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/legacy-client-B0ZUlbSQ.js +698 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/legacy-client-B0ZUlbSQ.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/package.json +3 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte.js +135 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_animate.js +57 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_animate.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_attachments.js +2 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_compiler.js +46691 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_compiler.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_easing.js +239 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_easing.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_events.js +2 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal.js +6 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_client.js +7 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_disclose-version.js +6 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_disclose-version.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_async.js +7 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_async.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_legacy.js +7 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_legacy.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_tracing.js +7 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_tracing.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_server.js +6 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_legacy.js +85 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_legacy.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_motion.js +561 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_motion.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity.js +26 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity_window.js +124 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity_window.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_server.js +2 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_store.js +91 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_store.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_transition.js +242 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_transition.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-lObbumRX.js +497 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-lObbumRX.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-mR9mAWyK.js +4929 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-mR9mAWyK.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/validate-CezNmRkM.js +192 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/validate-CezNmRkM.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/version-BHHo0WE-.js +10 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/version-BHHo0WE-.js.map +1 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/warnings-yiExAB06.js +140 -0
- package/dist/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/warnings-yiExAB06.js.map +1 -0
- package/dist/selection.js +0 -1
- package/package.json +11 -10
- package/src/DockNodeView.svelte +1 -1
- package/src/FlexRender.svelte +96 -96
- package/src/GridFooter.svelte +178 -179
- package/src/GridMenus.svelte +705 -782
- package/src/SvAutoComplete.svelte +165 -165
- package/src/SvAvatar.svelte +75 -75
- package/src/SvCalendar.svelte +503 -503
- package/src/SvCalendar.test.ts +226 -226
- package/src/SvCarousel.svelte +141 -141
- package/src/SvCheckBox.svelte +102 -102
- package/src/SvCircularProgress.svelte +109 -109
- package/src/SvColorInput.svelte +181 -181
- package/src/SvComboBox.svelte +275 -275
- package/src/SvContextMenu.svelte +116 -116
- package/src/SvCountryInput.svelte +160 -160
- package/src/SvDateRangeInput.svelte +1 -1
- package/src/SvDrawer.svelte +254 -254
- package/src/SvDropDownList.svelte +374 -374
- package/src/SvDurationInput.svelte +126 -126
- package/src/SvField.svelte +293 -293
- package/src/SvForm.svelte +437 -437
- package/src/SvForm.test.ts +411 -411
- package/src/SvGrid.controller.svelte.ts +3680 -3685
- package/src/SvGrid.css +2814 -2804
- package/src/SvGrid.svelte +3490 -3513
- package/src/SvGrid.types.ts +1708 -1709
- package/src/SvGridChart.svelte +1716 -1724
- package/src/SvGridChartPanel.svelte +485 -485
- package/src/SvGridChartView.svelte +70 -70
- package/src/SvGridDropdown.svelte +728 -728
- package/src/SvGridSelect.svelte +266 -268
- package/src/SvGroupCell.svelte +116 -116
- package/src/SvKbd.svelte +1 -1
- package/src/SvList.svelte +1 -1
- package/src/SvListBox.svelte +326 -326
- package/src/SvMaskedInput.svelte +122 -122
- package/src/SvMenu.svelte +124 -124
- package/src/SvMenu.test.ts +97 -97
- package/src/SvMenuList.svelte +146 -146
- package/src/SvMenubar.svelte +1 -1
- package/src/SvMultiSelect.svelte +289 -290
- package/src/SvNumberInput.svelte +168 -168
- package/src/SvOtpInput.svelte +158 -158
- package/src/SvPasswordInput.svelte +151 -151
- package/src/SvPhoneInput.svelte +133 -133
- package/src/SvPopover.svelte +197 -197
- package/src/SvProgress.svelte +116 -116
- package/src/SvRadioGroup.svelte +107 -107
- package/src/SvRating.svelte +112 -112
- package/src/SvResult.svelte +73 -73
- package/src/SvRichText.svelte +211 -207
- package/src/SvRowGroupPanel.svelte +170 -170
- package/src/SvScrollArea.svelte +61 -61
- package/src/SvSlider.svelte +200 -200
- package/src/SvSwitchButton.svelte +108 -108
- package/src/SvTagsInput.svelte +112 -112
- package/src/SvTextInput.svelte +147 -147
- package/src/SvTimePicker.svelte +245 -245
- package/src/SvToaster.svelte +159 -159
- package/src/SvToaster.test.ts +95 -95
- package/src/SvToggleButton.svelte +85 -85
- package/src/SvTooltip.svelte +161 -161
- package/src/SvTour.svelte +208 -204
- package/src/SvTree.svelte +444 -444
- package/src/SvTreeSelect.svelte +235 -237
- package/src/a11y/dismissable.test.ts +119 -119
- package/src/a11y/dismissable.ts +114 -114
- package/src/a11y.contract.test.ts +49 -49
- package/src/a11y.test.ts +59 -59
- package/src/a11y.ts +61 -61
- package/src/ai.test.ts +502 -502
- package/src/ai.ts +1391 -1391
- package/src/build-api.coverage.test.ts +633 -633
- package/src/build-api.ts +805 -910
- package/src/builtin-editors.grid.test.ts +85 -85
- package/src/cell-formatting.test.ts +1 -1
- package/src/cell-formatting.ts +169 -169
- package/src/cell-render.test.ts +513 -513
- package/src/cell-render.ts +496 -590
- package/src/cell-values.ts +118 -118
- package/src/chart-export.ts +201 -201
- package/src/chart-view.svelte.ts +36 -36
- package/src/chart.ts +2295 -2296
- package/src/clipboard.ts +0 -102
- package/src/collaboration.test.ts +104 -104
- package/src/collaboration.ts +167 -167
- package/src/columns.ts +7 -117
- package/src/core.performance.test.ts +30 -30
- package/src/core.ts +1261 -1261
- package/src/createAutocomplete.svelte.ts +132 -132
- package/src/createCombobox.svelte.ts +191 -191
- package/src/createCountryInput.svelte.ts +157 -157
- package/src/createDropdownList.svelte.ts +168 -168
- package/src/createForm.svelte.ts +386 -386
- package/src/createGrid.svelte.ts +42 -42
- package/src/createGrid.test.ts +10 -10
- package/src/createGridState.svelte.ts +17 -17
- package/src/createListbox.svelte.ts +250 -250
- package/src/createMenu.svelte.ts +224 -225
- package/src/createPopoverSelect.svelte.ts +213 -213
- package/src/createSlider.svelte.ts +191 -191
- package/src/createTooltip.svelte.ts +144 -144
- package/src/createTree.svelte.ts +319 -319
- package/src/editing.test.ts +949 -949
- package/src/editing.ts +606 -709
- package/src/editor-contract.ts +164 -164
- package/src/editor-registry.grid.test.ts +144 -146
- package/src/editor-registry.ts +122 -122
- package/src/export-data-api.test.ts +126 -126
- package/src/export-format.test.ts +107 -107
- package/src/export-format.ts +601 -598
- package/src/features.ts +0 -90
- package/src/filter-operators.ts +157 -157
- package/src/flex-render.ts +3 -3
- package/src/form-field.ts +127 -127
- package/src/group-display.test.ts +167 -167
- package/src/group-display.ts +200 -200
- package/src/index.ts +724 -724
- package/src/js-scroller.svelte.ts +173 -173
- package/src/keyboard-handlers.coverage.test.ts +1 -1
- package/src/keyboard-handlers.ts +270 -390
- package/src/keyboard.test.ts +59 -59
- package/src/keyboard.ts +97 -97
- package/src/list-nav.test.ts +49 -49
- package/src/list-nav.ts +29 -29
- package/src/list-option.test.ts +56 -56
- package/src/list-option.ts +172 -172
- package/src/menus.test.ts +0 -1
- package/src/menus.ts +567 -679
- package/src/merge-objects.ts +48 -48
- package/src/new-features.test.ts +3 -1
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/_svelte_metadata.json +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/_metadata.json +178 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/attachments-qzRy9DX4.js +3843 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/attachments-qzRy9DX4.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/constants-RLNOXCpz.js +23 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/constants-RLNOXCpz.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/dev-DPd12uEU.js +1925 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/dev-DPd12uEU.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/events-CDC4DKuQ.js +206 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/events-CDC4DKuQ.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/flags-BD-lYX7s.js +20 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/flags-BD-lYX7s.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/hydration-D3UBU2t8.js +264 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/hydration-D3UBU2t8.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/legacy-client-B0ZUlbSQ.js +698 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/legacy-client-B0ZUlbSQ.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/package.json +3 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte.js +135 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_animate.js +57 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_animate.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_attachments.js +2 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_compiler.js +46691 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_compiler.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_easing.js +239 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_easing.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_events.js +2 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal.js +6 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_client.js +7 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_disclose-version.js +6 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_disclose-version.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_async.js +7 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_async.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_legacy.js +7 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_legacy.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_tracing.js +7 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_flags_tracing.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_internal_server.js +6 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_legacy.js +85 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_legacy.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_motion.js +561 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_motion.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity.js +26 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity_window.js +124 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_reactivity_window.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_server.js +2 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_store.js +91 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_store.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_transition.js +242 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/svelte_transition.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-lObbumRX.js +497 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-lObbumRX.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-mR9mAWyK.js +4929 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/utils-mR9mAWyK.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/validate-CezNmRkM.js +192 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/validate-CezNmRkM.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/version-BHHo0WE-.js +10 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/version-BHHo0WE-.js.map +1 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/warnings-yiExAB06.js +140 -0
- package/src/node_modules/.vite/vitest/67d8ed22ed986c5e2e948f64d892f30be166cc36/deps___vitest__/warnings-yiExAB06.js.map +1 -0
- package/src/overlays.test.ts +90 -90
- package/src/render-component.ts +28 -28
- package/src/row-drag.test.ts +1 -1
- package/src/row-resize.test.ts +1 -2
- package/src/row-resize.ts +210 -210
- package/src/scheduler-model.test.ts +562 -562
- package/src/scheduler-model.ts +872 -872
- package/src/scroll-sync.test.ts +4 -7
- package/src/scroll-sync.ts +0 -122
- package/src/selection.test.ts +754 -754
- package/src/selection.ts +491 -600
- package/src/server-data-source.test.ts +289 -289
- package/src/server-data-source.ts +413 -413
- package/src/server-group-model.test.ts +2 -2
- package/src/sparkline.test.ts +68 -68
- package/src/sparkline.ts +169 -169
- package/src/spreadsheet.test.ts +488 -488
- package/src/spreadsheet.ts +312 -312
- package/src/static-functions.ts +11 -11
- package/src/subscribe.ts +38 -38
- package/src/summaries.ts +0 -112
- package/src/svgrid-wrapper.types.ts +526 -526
- package/src/svgrid.async-editor-options.test.ts +271 -271
- package/src/svgrid.auto-row-height.test.ts +204 -204
- package/src/svgrid.behavior.test.ts +705 -706
- package/src/svgrid.charting.test.ts +534 -534
- package/src/svgrid.column-reorder.test.ts +0 -8
- package/src/svgrid.comments-autocomplete.test.ts +123 -123
- package/src/svgrid.context-menu.test.ts +147 -147
- package/src/svgrid.features.test.ts +157 -157
- package/src/svgrid.filter-depth.test.ts +163 -163
- package/src/svgrid.filter-menu-listbox.svelte.test.ts +322 -322
- package/src/svgrid.filter-menu-scroll.test.ts +112 -112
- package/src/svgrid.footer-pagesize.svelte.test.ts +86 -0
- package/src/svgrid.grand-total.test.ts +188 -188
- package/src/svgrid.group-display-mode.test.ts +171 -171
- package/src/svgrid.group-footers.test.ts +121 -121
- package/src/svgrid.group-pagination.test.ts +153 -153
- package/src/svgrid.new-features.wrapper.test.ts +251 -251
- package/src/svgrid.tree-data.test.ts +186 -186
- package/src/svgrid.wrapper.test.ts +40 -40
- package/src/svgriddropdown.async-panel.svelte.test.ts +195 -195
- package/src/test-setup.ts +62 -62
- package/src/themes/index.ts +257 -257
- package/src/toast-store.svelte.ts +246 -246
- package/src/toast-store.test.ts +147 -147
- package/src/tree-row-model.test.ts +168 -169
- package/src/ui-buttons.test.ts +144 -144
- package/src/ui-inputs.test.ts +118 -118
- package/src/ui-localization.test.ts +113 -113
- package/src/ui-range.test.ts +70 -70
- package/src/ui-selection.test.ts +155 -155
- package/src/ui-tier1.test.ts +142 -142
- package/src/virtual.test.ts +88 -88
- package/src/virtualization/column-virtualizer.test.ts +27 -27
- package/src/virtualization/column-virtualizer.ts +30 -30
- package/src/virtualization/svelte-virtualizer.svelte.ts +26 -26
- package/src/virtualization/types.ts +30 -30
- package/src/virtualization/virtualizer.test.ts +47 -47
- package/src/virtualization/virtualizer.ts +296 -296
- package/dist/cdn/disclose-version-DoD9AFD_.js +0 -2958
package/src/ai.ts
CHANGED
|
@@ -1,1391 +1,1391 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pro AI feature pack
|
|
3
|
-
* -------------------
|
|
4
|
-
*
|
|
5
|
-
* Three jobs every analyst wishes a data grid could do:
|
|
6
|
-
*
|
|
7
|
-
* 1. Natural-language filter / sort (`aiFilter`)
|
|
8
|
-
* "show me deals closing this quarter over $50k owned by Sasha"
|
|
9
|
-
* -> { filters: [...], sort: [...] }
|
|
10
|
-
*
|
|
11
|
-
* 2. Smart fill (`aiSmartFill`)
|
|
12
|
-
* User edits two cells in a column with example values; the
|
|
13
|
-
* Grid proposes the rest. Excel "Flash Fill" pattern.
|
|
14
|
-
*
|
|
15
|
-
* 3. Summarise rows (`aiSummarize`)
|
|
16
|
-
* Single row, the current selection, a group key, or the whole
|
|
17
|
-
* filtered view -> a one-paragraph summary.
|
|
18
|
-
*
|
|
19
|
-
* The grid stays headless / model-agnostic. The consumer supplies an
|
|
20
|
-
* `AIProvider` that knows how to call OpenAI / Anthropic / a local
|
|
21
|
-
* model / a server-side proxy. We never bundle a model client.
|
|
22
|
-
*
|
|
23
|
-
* Built-in + free: the AI helpers live in `@svgrid/grid`. They ship no model
|
|
24
|
-
* client and do nothing until you register a provider with `setAIProvider(...)`,
|
|
25
|
-
* so they add nothing to the base bundle unless you actually use them.
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
import type { RowData, SvGridApi, TableFeatures } from './index'
|
|
29
|
-
import { getExportProvider } from './export-provider'
|
|
30
|
-
|
|
31
|
-
// Export formats an AI export can plan. WRITING the enterprise formats (xlsx /
|
|
32
|
-
// pdf / html / xml / md) needs the export engine from `@svgrid/enterprise`
|
|
33
|
-
// (registered via the export-provider seam); csv / tsv / json are also handled
|
|
34
|
-
// by that engine when present. The union is declared locally so the free grid
|
|
35
|
-
// carries no dependency on the enterprise export module.
|
|
36
|
-
type ExportFormat = 'xlsx' | 'xls' | 'pdf' | 'csv' | 'tsv' | 'html' | 'json' | 'xml' | 'md'
|
|
37
|
-
|
|
38
|
-
// ---------------------------------------------------------------------------
|
|
39
|
-
// Provider contract
|
|
40
|
-
// ---------------------------------------------------------------------------
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Shape every consumer-provided model adapter must implement. Keeping this
|
|
44
|
-
* tiny (one async call, two response formats) lets the same adapter drive
|
|
45
|
-
* OpenAI's `chat.completions`, Anthropic's `messages`, a self-hosted
|
|
46
|
-
* llama.cpp endpoint, or a server-side proxy. The grid only cares that the
|
|
47
|
-
* provider eventually returns a string we can parse.
|
|
48
|
-
*/
|
|
49
|
-
export type AIProvider = (request: AIRequest) => Promise<string>
|
|
50
|
-
|
|
51
|
-
export type AIRequest = {
|
|
52
|
-
/** Full prompt the grid built for the model. Already includes column
|
|
53
|
-
* schema and any sampled rows where applicable. */
|
|
54
|
-
prompt: string
|
|
55
|
-
/** When 'json', the provider should ask the model to return strict
|
|
56
|
-
* JSON only - no prose. We parse the response with JSON.parse and
|
|
57
|
-
* throw a typed error on failure. */
|
|
58
|
-
responseFormat?: 'text' | 'json'
|
|
59
|
-
/** Honored if the underlying transport supports cancellation. */
|
|
60
|
-
signal?: AbortSignal
|
|
61
|
-
/** Free-form tag for telemetry / logging. One of: 'filter',
|
|
62
|
-
* 'smart-fill', 'summarize', 'classify'. */
|
|
63
|
-
task: AITask
|
|
64
|
-
/** Soft hint to the provider about how many tokens we expect back.
|
|
65
|
-
* Useful for routing small jobs to a cheaper model. */
|
|
66
|
-
maxOutputTokens?: number
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export type AITask = 'filter' | 'smart-fill' | 'summarize' | 'classify' | 'export' | 'anomaly' | 'chart'
|
|
70
|
-
|
|
71
|
-
let provider: AIProvider | null = null
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Register the model adapter every AI call will route through. Call once
|
|
75
|
-
* at app boot. Passing `null` clears the provider and AI calls revert to
|
|
76
|
-
* throwing "no provider" errors.
|
|
77
|
-
*/
|
|
78
|
-
export function setAIProvider(p: AIProvider | null): void {
|
|
79
|
-
provider = p
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function getAIProvider(): AIProvider | null {
|
|
83
|
-
return provider
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export function hasAIProvider(): boolean {
|
|
87
|
-
return provider != null
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
class NoProviderError extends Error {
|
|
91
|
-
constructor() {
|
|
92
|
-
super(
|
|
93
|
-
'@svgrid/grid ai: no AI provider registered. Call setAIProvider(fn) ' +
|
|
94
|
-
'with an adapter that talks to OpenAI / Anthropic / your proxy.',
|
|
95
|
-
)
|
|
96
|
-
this.name = 'NoProviderError'
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
class BadJsonError extends Error {
|
|
101
|
-
constructor(raw: string) {
|
|
102
|
-
super(
|
|
103
|
-
'@svgrid/grid ai: provider returned non-JSON for a json-format request. ' +
|
|
104
|
-
`First 200 chars: ${raw.slice(0, 200)}`,
|
|
105
|
-
)
|
|
106
|
-
this.name = 'BadJsonError'
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
async function callProvider(req: AIRequest): Promise<string> {
|
|
111
|
-
if (!provider) throw new NoProviderError()
|
|
112
|
-
return provider(req)
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
async function callJSON<T>(req: AIRequest): Promise<T> {
|
|
116
|
-
const raw = await callProvider({ ...req, responseFormat: 'json' })
|
|
117
|
-
// Models occasionally wrap JSON in markdown code fences even when asked
|
|
118
|
-
// for raw JSON. Strip a single fenced block if present, then parse.
|
|
119
|
-
const stripped = raw.trim().replace(/^```(?:json)?\s*|\s*```$/g, '')
|
|
120
|
-
try {
|
|
121
|
-
return JSON.parse(stripped) as T
|
|
122
|
-
} catch {
|
|
123
|
-
throw new BadJsonError(raw)
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// ---------------------------------------------------------------------------
|
|
128
|
-
// Helpers - build column schema + row sample from the grid API
|
|
129
|
-
// ---------------------------------------------------------------------------
|
|
130
|
-
|
|
131
|
-
type ColumnSchemaEntry = {
|
|
132
|
-
field: string
|
|
133
|
-
type: 'string' | 'number' | 'boolean' | 'date' | 'unknown'
|
|
134
|
-
sampleValues: unknown[]
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Inspect the first N rows the grid is holding to infer a typed schema +
|
|
139
|
-
* a handful of sample values per column. This is the context every AI
|
|
140
|
-
* task needs and the most expensive thing to build, so the helpers cache
|
|
141
|
-
* the result inside one task call rather than calling api.getData()
|
|
142
|
-
* repeatedly.
|
|
143
|
-
*/
|
|
144
|
-
function buildColumnSchema<
|
|
145
|
-
TFeatures extends TableFeatures,
|
|
146
|
-
TData extends RowData,
|
|
147
|
-
>(api: SvGridApi<TFeatures, TData>, sampleSize = 50): ColumnSchemaEntry[] {
|
|
148
|
-
const data = api.getData()
|
|
149
|
-
if (data.length === 0) return []
|
|
150
|
-
const slice = data.slice(0, Math.min(data.length, sampleSize))
|
|
151
|
-
const fields = new Set<string>()
|
|
152
|
-
for (const row of slice) {
|
|
153
|
-
for (const k of Object.keys(row as object)) fields.add(k)
|
|
154
|
-
}
|
|
155
|
-
const out: ColumnSchemaEntry[] = []
|
|
156
|
-
for (const field of fields) {
|
|
157
|
-
const values: unknown[] = []
|
|
158
|
-
for (const row of slice) {
|
|
159
|
-
const v = (row as Record<string, unknown>)[field]
|
|
160
|
-
if (v != null) values.push(v)
|
|
161
|
-
if (values.length >= 5) break
|
|
162
|
-
}
|
|
163
|
-
out.push({
|
|
164
|
-
field,
|
|
165
|
-
type: inferType(values),
|
|
166
|
-
sampleValues: values,
|
|
167
|
-
})
|
|
168
|
-
}
|
|
169
|
-
return out
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function inferType(samples: unknown[]): ColumnSchemaEntry['type'] {
|
|
173
|
-
if (samples.length === 0) return 'unknown'
|
|
174
|
-
const v = samples[0]
|
|
175
|
-
if (typeof v === 'number') return 'number'
|
|
176
|
-
if (typeof v === 'boolean') return 'boolean'
|
|
177
|
-
if (typeof v === 'string') {
|
|
178
|
-
// Cheap ISO-date sniff so we route date-style filters correctly.
|
|
179
|
-
if (/^\d{4}-\d{2}-\d{2}/.test(v)) return 'date'
|
|
180
|
-
return 'string'
|
|
181
|
-
}
|
|
182
|
-
return 'unknown'
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function schemaToPromptBlock(schema: ColumnSchemaEntry[]): string {
|
|
186
|
-
return schema
|
|
187
|
-
.map(
|
|
188
|
-
(c) =>
|
|
189
|
-
`- ${c.field} (${c.type}): e.g. ${c.sampleValues
|
|
190
|
-
.slice(0, 3)
|
|
191
|
-
.map((v) => JSON.stringify(v))
|
|
192
|
-
.join(', ')}`,
|
|
193
|
-
)
|
|
194
|
-
.join('\n')
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// ---------------------------------------------------------------------------
|
|
198
|
-
// 1. Natural-language filter / sort
|
|
199
|
-
// ---------------------------------------------------------------------------
|
|
200
|
-
|
|
201
|
-
export type AIFilterClause = {
|
|
202
|
-
field: string
|
|
203
|
-
operator: 'contains' | 'equals' | 'startsWith' | 'greaterThan' | 'lessThan' | 'isBlank'
|
|
204
|
-
value?: string
|
|
205
|
-
}
|
|
206
|
-
export type AISortClause = { field: string; desc: boolean }
|
|
207
|
-
|
|
208
|
-
export type AIFilterResult = {
|
|
209
|
-
filters: AIFilterClause[]
|
|
210
|
-
sort: AISortClause[]
|
|
211
|
-
/** Plain-English explanation of how the model interpreted the query.
|
|
212
|
-
* Surface this in the UI so the user can confirm or undo. */
|
|
213
|
-
rationale: string
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
export type AIFilterOptions = {
|
|
217
|
-
/**
|
|
218
|
-
* When true, the helper not only RETURNS the plan but also applies it
|
|
219
|
-
* to the grid via `api.setFilter` / `api.setSort`. Defaults to false
|
|
220
|
-
* so callers can show a preview before committing.
|
|
221
|
-
*/
|
|
222
|
-
apply?: boolean
|
|
223
|
-
signal?: AbortSignal
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* Translate a natural-language query into a filter+sort plan against
|
|
228
|
-
* the current grid's columns. The grid passes the column schema (names,
|
|
229
|
-
* types, sample values) to the model so it can pick the right field
|
|
230
|
-
* names without hallucinating.
|
|
231
|
-
*/
|
|
232
|
-
export async function aiFilter<
|
|
233
|
-
TFeatures extends TableFeatures,
|
|
234
|
-
TData extends RowData,
|
|
235
|
-
>(
|
|
236
|
-
api: SvGridApi<TFeatures, TData>,
|
|
237
|
-
query: string,
|
|
238
|
-
opts: AIFilterOptions = {},
|
|
239
|
-
): Promise<AIFilterResult> {
|
|
240
|
-
const schema = buildColumnSchema(api)
|
|
241
|
-
const prompt =
|
|
242
|
-
`You are a data-grid filter planner. Translate the user's natural-language ` +
|
|
243
|
-
`query into a strict-JSON plan that the grid can apply.\n\n` +
|
|
244
|
-
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
245
|
-
`Output JSON schema:\n` +
|
|
246
|
-
`{ "filters": [{"field": "<one of the columns above>", ` +
|
|
247
|
-
`"operator": "contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank", ` +
|
|
248
|
-
`"value": "<string>"}], ` +
|
|
249
|
-
`"sort": [{"field": "<column>", "desc": true|false}], ` +
|
|
250
|
-
`"rationale": "<one-sentence explanation>" }\n\n` +
|
|
251
|
-
`User query: ${query}\n\n` +
|
|
252
|
-
`Return JSON only, no prose.`
|
|
253
|
-
|
|
254
|
-
const result = await callJSON<AIFilterResult>({
|
|
255
|
-
prompt,
|
|
256
|
-
task: 'filter',
|
|
257
|
-
signal: opts.signal,
|
|
258
|
-
maxOutputTokens: 400,
|
|
259
|
-
})
|
|
260
|
-
|
|
261
|
-
// Defensive: drop anything that doesn't match a real column. Models love
|
|
262
|
-
// to invent plausible-sounding field names; we'd rather skip a clause
|
|
263
|
-
// than throw at runtime.
|
|
264
|
-
const valid = new Set(schema.map((c) => c.field))
|
|
265
|
-
result.filters = (result.filters ?? []).filter((f) => valid.has(f.field))
|
|
266
|
-
result.sort = (result.sort ?? []).filter((s) => valid.has(s.field))
|
|
267
|
-
|
|
268
|
-
if (opts.apply) {
|
|
269
|
-
api.clearAllFilters()
|
|
270
|
-
api.clearSort()
|
|
271
|
-
for (const f of result.filters) {
|
|
272
|
-
api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
|
|
273
|
-
}
|
|
274
|
-
// Multiple sort clauses get applied last-wins because the public
|
|
275
|
-
// `setSort` is single-key. Multi-sort is on the roadmap.
|
|
276
|
-
const last = result.sort[result.sort.length - 1]
|
|
277
|
-
if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
return result
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
// ---------------------------------------------------------------------------
|
|
284
|
-
// 2. Smart fill
|
|
285
|
-
// ---------------------------------------------------------------------------
|
|
286
|
-
|
|
287
|
-
export type AISmartFillExample = { input: Record<string, unknown>; output: unknown }
|
|
288
|
-
|
|
289
|
-
export type AISmartFillResult<TValue = unknown> = {
|
|
290
|
-
field: string
|
|
291
|
-
predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
|
|
292
|
-
rationale: string
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
export type AISmartFillOptions = {
|
|
296
|
-
/** Target column - the one whose values we want filled. */
|
|
297
|
-
field: string
|
|
298
|
-
/** Index of rows the model should propose values for. If omitted, every
|
|
299
|
-
* row whose current `field` value is `null`, `undefined` or `''` is
|
|
300
|
-
* selected automatically. */
|
|
301
|
-
targetRowIndices?: number[]
|
|
302
|
-
/**
|
|
303
|
-
* Worked examples the user has already filled in. Required - the
|
|
304
|
-
* model needs at least one to know the pattern, two or more to lock
|
|
305
|
-
* the schema. We don't pull these from the grid automatically because
|
|
306
|
-
* "edited" vs "untouched" isn't a state SvGrid exposes today.
|
|
307
|
-
*/
|
|
308
|
-
examples: AISmartFillExample[]
|
|
309
|
-
signal?: AbortSignal
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Given a column and a few user-provided examples, propose values for the
|
|
314
|
-
* untouched rows. Returns predictions only - the caller chooses whether to
|
|
315
|
-
* commit them via `api.setCellValue`. This is the right shape for an
|
|
316
|
-
* accept-per-cell UX with confidence-coloured highlights.
|
|
317
|
-
*/
|
|
318
|
-
export async function aiSmartFill<
|
|
319
|
-
TFeatures extends TableFeatures,
|
|
320
|
-
TData extends RowData,
|
|
321
|
-
TValue = unknown,
|
|
322
|
-
>(
|
|
323
|
-
api: SvGridApi<TFeatures, TData>,
|
|
324
|
-
opts: AISmartFillOptions,
|
|
325
|
-
): Promise<AISmartFillResult<TValue>> {
|
|
326
|
-
if (opts.examples.length === 0) {
|
|
327
|
-
throw new Error('@svgrid/grid ai: aiSmartFill requires at least one example.')
|
|
328
|
-
}
|
|
329
|
-
const data = api.getData()
|
|
330
|
-
const targets =
|
|
331
|
-
opts.targetRowIndices ??
|
|
332
|
-
data
|
|
333
|
-
.map((row, i) => {
|
|
334
|
-
const v = (row as Record<string, unknown>)[opts.field]
|
|
335
|
-
return v == null || v === '' ? i : -1
|
|
336
|
-
})
|
|
337
|
-
.filter((i) => i >= 0)
|
|
338
|
-
|
|
339
|
-
if (targets.length === 0) {
|
|
340
|
-
return { field: opts.field, predictions: [], rationale: 'No empty cells to fill.' }
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
const examplesBlock = opts.examples
|
|
344
|
-
.map((ex, i) => `Example ${i + 1}: input=${JSON.stringify(ex.input)} -> output=${JSON.stringify(ex.output)}`)
|
|
345
|
-
.join('\n')
|
|
346
|
-
|
|
347
|
-
const targetRowsBlock = targets
|
|
348
|
-
.map((i) => `Row ${i}: ${JSON.stringify(data[i])}`)
|
|
349
|
-
.join('\n')
|
|
350
|
-
|
|
351
|
-
const prompt =
|
|
352
|
-
`You are filling in a single column of a data grid based on user-provided ` +
|
|
353
|
-
`examples. Match the pattern in the examples exactly.\n\n` +
|
|
354
|
-
`Target column: ${opts.field}\n\n` +
|
|
355
|
-
`Examples:\n${examplesBlock}\n\n` +
|
|
356
|
-
`Rows to fill:\n${targetRowsBlock}\n\n` +
|
|
357
|
-
`Return strict JSON only:\n` +
|
|
358
|
-
`{ "predictions": [{"rowIndex": <number>, "value": <inferred value>, ` +
|
|
359
|
-
`"confidence": <0..1>}], "rationale": "<one-sentence pattern description>" }`
|
|
360
|
-
|
|
361
|
-
const result = await callJSON<{
|
|
362
|
-
predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
|
|
363
|
-
rationale: string
|
|
364
|
-
}>({
|
|
365
|
-
prompt,
|
|
366
|
-
task: 'smart-fill',
|
|
367
|
-
signal: opts.signal,
|
|
368
|
-
maxOutputTokens: 600,
|
|
369
|
-
})
|
|
370
|
-
|
|
371
|
-
return {
|
|
372
|
-
field: opts.field,
|
|
373
|
-
predictions: result.predictions ?? [],
|
|
374
|
-
rationale: result.rationale ?? '',
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
// ---------------------------------------------------------------------------
|
|
379
|
-
// 3. Summarise
|
|
380
|
-
// ---------------------------------------------------------------------------
|
|
381
|
-
|
|
382
|
-
export type AISummarizeTarget =
|
|
383
|
-
| { kind: 'row'; rowIndex: number }
|
|
384
|
-
| { kind: 'all' }
|
|
385
|
-
| { kind: 'selection'; rowIndices: number[] }
|
|
386
|
-
| { kind: 'group'; field: string; value: unknown }
|
|
387
|
-
|
|
388
|
-
export type AISummary = {
|
|
389
|
-
text: string
|
|
390
|
-
bullets: string[]
|
|
391
|
-
/** Field names the model thinks are the most load-bearing for the
|
|
392
|
-
* story it just told. UI can highlight those columns. */
|
|
393
|
-
highlightedFields: string[]
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
export type AISummarizeOptions = {
|
|
397
|
-
target: AISummarizeTarget
|
|
398
|
-
/** Optional question the user is trying to answer. Helps the model
|
|
399
|
-
* bias the summary toward the relevant columns. */
|
|
400
|
-
question?: string
|
|
401
|
-
signal?: AbortSignal
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/**
|
|
405
|
-
* Ask the model to summarise a slice of the grid. Caps the row sample at
|
|
406
|
-
* a model-friendly size; for huge selections it samples uniformly so the
|
|
407
|
-
* summary stays representative without blowing the context window.
|
|
408
|
-
*/
|
|
409
|
-
export async function aiSummarize<
|
|
410
|
-
TFeatures extends TableFeatures,
|
|
411
|
-
TData extends RowData,
|
|
412
|
-
>(
|
|
413
|
-
api: SvGridApi<TFeatures, TData>,
|
|
414
|
-
opts: AISummarizeOptions,
|
|
415
|
-
): Promise<AISummary> {
|
|
416
|
-
const all = api.getData()
|
|
417
|
-
const rows: TData[] = (() => {
|
|
418
|
-
const t = opts.target
|
|
419
|
-
if (t.kind === 'row') {
|
|
420
|
-
const r = all[t.rowIndex]
|
|
421
|
-
return r ? [r] : []
|
|
422
|
-
}
|
|
423
|
-
if (t.kind === 'selection') {
|
|
424
|
-
return t.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
|
|
425
|
-
}
|
|
426
|
-
if (t.kind === 'group') {
|
|
427
|
-
return all.filter((r) => (r as Record<string, unknown>)[t.field] === t.value)
|
|
428
|
-
}
|
|
429
|
-
return all.slice()
|
|
430
|
-
})()
|
|
431
|
-
|
|
432
|
-
if (rows.length === 0) {
|
|
433
|
-
return { text: 'No rows in scope.', bullets: [], highlightedFields: [] }
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
// Uniform sample to stay inside a sensible context budget.
|
|
437
|
-
const MAX_SAMPLE = 25
|
|
438
|
-
const sample = rows.length <= MAX_SAMPLE
|
|
439
|
-
? rows
|
|
440
|
-
: Array.from({ length: MAX_SAMPLE }, (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!)
|
|
441
|
-
|
|
442
|
-
const schema = buildColumnSchema(api, 30)
|
|
443
|
-
const prompt =
|
|
444
|
-
`You are summarising a slice of a business data grid for a busy analyst.\n\n` +
|
|
445
|
-
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
446
|
-
`Slice size: ${rows.length} row(s). Sampled rows shown below.\n` +
|
|
447
|
-
`${sample.map((r) => JSON.stringify(r)).join('\n')}\n\n` +
|
|
448
|
-
(opts.question ? `User's question: ${opts.question}\n\n` : '') +
|
|
449
|
-
`Return strict JSON only:\n` +
|
|
450
|
-
`{ "text": "<one short paragraph>", ` +
|
|
451
|
-
`"bullets": ["<3-5 punchy bullets>"], ` +
|
|
452
|
-
`"highlightedFields": ["<column names the summary leans on>"] }`
|
|
453
|
-
|
|
454
|
-
const result = await callJSON<AISummary>({
|
|
455
|
-
prompt,
|
|
456
|
-
task: 'summarize',
|
|
457
|
-
signal: opts.signal,
|
|
458
|
-
maxOutputTokens: 600,
|
|
459
|
-
})
|
|
460
|
-
return {
|
|
461
|
-
text: result.text ?? '',
|
|
462
|
-
bullets: result.bullets ?? [],
|
|
463
|
-
highlightedFields: result.highlightedFields ?? [],
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
// ---------------------------------------------------------------------------
|
|
468
|
-
// 4. Classify (free-text -> bucketed value)
|
|
469
|
-
// ---------------------------------------------------------------------------
|
|
470
|
-
|
|
471
|
-
export type AIClassifyOptions = {
|
|
472
|
-
/** Column whose free-text we're classifying. */
|
|
473
|
-
inputField: string
|
|
474
|
-
/** Target column the model should write to. */
|
|
475
|
-
outputField: string
|
|
476
|
-
/** Allowed values. The model is constrained to pick one. */
|
|
477
|
-
classes: string[]
|
|
478
|
-
/** Optional one-line description of each class (acts as a labeling rubric). */
|
|
479
|
-
classDescriptions?: Record<string, string>
|
|
480
|
-
/** Rows to classify. Defaults to all. */
|
|
481
|
-
targetRowIndices?: number[]
|
|
482
|
-
signal?: AbortSignal
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
export type AIClassifyResult = {
|
|
486
|
-
inputField: string
|
|
487
|
-
outputField: string
|
|
488
|
-
predictions: Array<{ rowIndex: number; value: string; confidence: number }>
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
/**
|
|
492
|
-
* Bucket free-text cells into one of a known set of classes. The model
|
|
493
|
-
* is constrained to pick from `opts.classes`; predictions outside the set
|
|
494
|
-
* are dropped so the caller can rely on the output being clean enum
|
|
495
|
-
* values it can write straight back into the grid.
|
|
496
|
-
*/
|
|
497
|
-
export async function aiClassify<
|
|
498
|
-
TFeatures extends TableFeatures,
|
|
499
|
-
TData extends RowData,
|
|
500
|
-
>(
|
|
501
|
-
api: SvGridApi<TFeatures, TData>,
|
|
502
|
-
opts: AIClassifyOptions,
|
|
503
|
-
): Promise<AIClassifyResult> {
|
|
504
|
-
const data = api.getData()
|
|
505
|
-
const targets = opts.targetRowIndices ?? data.map((_, i) => i)
|
|
506
|
-
const rubric = opts.classDescriptions
|
|
507
|
-
? Object.entries(opts.classDescriptions)
|
|
508
|
-
.map(([k, v]) => `- ${k}: ${v}`)
|
|
509
|
-
.join('\n')
|
|
510
|
-
: opts.classes.map((c) => `- ${c}`).join('\n')
|
|
511
|
-
|
|
512
|
-
const rowsBlock = targets
|
|
513
|
-
.map((i) => `Row ${i}: ${JSON.stringify((data[i] as Record<string, unknown>)?.[opts.inputField] ?? '')}`)
|
|
514
|
-
.join('\n')
|
|
515
|
-
|
|
516
|
-
const prompt =
|
|
517
|
-
`You are a strict text classifier. For each row, pick exactly one ` +
|
|
518
|
-
`label from the list. If unsure, pick the closest match and lower the ` +
|
|
519
|
-
`confidence.\n\n` +
|
|
520
|
-
`Allowed labels (with optional rubric):\n${rubric}\n\n` +
|
|
521
|
-
`Rows to classify (text from column "${opts.inputField}"):\n${rowsBlock}\n\n` +
|
|
522
|
-
`Return strict JSON only:\n` +
|
|
523
|
-
`{ "predictions": [{"rowIndex": <number>, "value": "<label>", "confidence": <0..1>}] }`
|
|
524
|
-
|
|
525
|
-
const result = await callJSON<{
|
|
526
|
-
predictions: Array<{ rowIndex: number; value: string; confidence: number }>
|
|
527
|
-
}>({
|
|
528
|
-
prompt,
|
|
529
|
-
task: 'classify',
|
|
530
|
-
signal: opts.signal,
|
|
531
|
-
maxOutputTokens: Math.min(2000, 30 + targets.length * 30),
|
|
532
|
-
})
|
|
533
|
-
|
|
534
|
-
const allowed = new Set(opts.classes)
|
|
535
|
-
return {
|
|
536
|
-
inputField: opts.inputField,
|
|
537
|
-
outputField: opts.outputField,
|
|
538
|
-
predictions: (result.predictions ?? []).filter((p) => allowed.has(p.value)),
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
// ---------------------------------------------------------------------------
|
|
543
|
-
// 5. Natural-language export
|
|
544
|
-
// ---------------------------------------------------------------------------
|
|
545
|
-
|
|
546
|
-
const EXPORT_FORMATS: ExportFormat[] = ['xlsx', 'xls', 'pdf', 'csv', 'tsv', 'html', 'json', 'xml', 'md']
|
|
547
|
-
|
|
548
|
-
export type AIExportPlan = {
|
|
549
|
-
format: ExportFormat
|
|
550
|
-
filters: AIFilterClause[]
|
|
551
|
-
sort: AISortClause[]
|
|
552
|
-
groupBy: string[]
|
|
553
|
-
/** Plain-English explanation of how the model read the request. */
|
|
554
|
-
rationale: string
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
export type AIExportOptions = {
|
|
558
|
-
/**
|
|
559
|
-
* Also apply the filter / sort / grouping to the grid (mutating the view) so
|
|
560
|
-
* it mirrors the export. Default FALSE - the export is self-contained (it
|
|
561
|
-
* computes its own rows), so the grid is left untouched unless you opt in.
|
|
562
|
-
*/
|
|
563
|
-
apply?: boolean
|
|
564
|
-
/** Actually download the file. Default true; set false to preview the plan. */
|
|
565
|
-
run?: boolean
|
|
566
|
-
/** Base filename (no extension). Default 'export'. */
|
|
567
|
-
filename?: string
|
|
568
|
-
signal?: AbortSignal
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
/**
|
|
572
|
-
* Turn a natural-language request ("export EU orders from Q2 as a grouped PDF")
|
|
573
|
-
* into an export: the model returns a `{ format, filters, sort, groupBy }` plan
|
|
574
|
-
* against the grid's columns; we apply the filter/sort to the grid and hand the
|
|
575
|
-
* result to the registered export engine (@svgrid/enterprise). Returns the plan
|
|
576
|
-
* so the UI can show what it did (or preview it first with `run: false`).
|
|
577
|
-
*/
|
|
578
|
-
export async function aiExport<
|
|
579
|
-
TFeatures extends TableFeatures,
|
|
580
|
-
TData extends RowData,
|
|
581
|
-
>(
|
|
582
|
-
api: SvGridApi<TFeatures, TData>,
|
|
583
|
-
query: string,
|
|
584
|
-
opts: AIExportOptions = {},
|
|
585
|
-
): Promise<AIExportPlan> {
|
|
586
|
-
const schema = buildColumnSchema(api)
|
|
587
|
-
const prompt =
|
|
588
|
-
`You are an export assistant for a data grid. Translate the user's request ` +
|
|
589
|
-
`into a strict-JSON export plan.\n\n` +
|
|
590
|
-
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
591
|
-
`Output JSON schema:\n` +
|
|
592
|
-
`{ "format": "xlsx"|"xls"|"pdf"|"csv"|"tsv"|"html"|"json"|"xml"|"md", ` +
|
|
593
|
-
`"filters": [{"field":"<column>","operator":"contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank","value":"<string>"}], ` +
|
|
594
|
-
`"sort": [{"field":"<column>","desc":true|false}], ` +
|
|
595
|
-
`"groupBy": ["<column>"], ` +
|
|
596
|
-
`"rationale": "<one sentence>" }\n\n` +
|
|
597
|
-
`Rules: use the format the user names (default "xlsx"); only use column ` +
|
|
598
|
-
`names from the list above; "grouped" / "group by X" -> groupBy. ` +
|
|
599
|
-
`Return JSON only, no prose.\n\n` +
|
|
600
|
-
`User request: ${query}`
|
|
601
|
-
|
|
602
|
-
const plan = await callJSON<AIExportPlan>({
|
|
603
|
-
prompt,
|
|
604
|
-
task: 'export',
|
|
605
|
-
signal: opts.signal,
|
|
606
|
-
maxOutputTokens: 500,
|
|
607
|
-
})
|
|
608
|
-
|
|
609
|
-
// Defensive validation - drop invented fields, clamp the format.
|
|
610
|
-
const valid = new Set(schema.map((c) => c.field))
|
|
611
|
-
plan.format = EXPORT_FORMATS.includes(plan.format) ? plan.format : 'xlsx'
|
|
612
|
-
plan.filters = (plan.filters ?? []).filter((f) => valid.has(f.field))
|
|
613
|
-
plan.sort = (plan.sort ?? []).filter((s) => valid.has(s.field))
|
|
614
|
-
plan.groupBy = (plan.groupBy ?? []).filter((g) => valid.has(g))
|
|
615
|
-
plan.rationale = plan.rationale ?? ''
|
|
616
|
-
|
|
617
|
-
// Optionally mirror the plan onto the grid (opt-in). Off by default so the
|
|
618
|
-
// export never disturbs the user's current view.
|
|
619
|
-
if (opts.apply === true) {
|
|
620
|
-
api.clearAllFilters()
|
|
621
|
-
api.clearSort()
|
|
622
|
-
for (const f of plan.filters) {
|
|
623
|
-
api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
|
|
624
|
-
}
|
|
625
|
-
const last = plan.sort[plan.sort.length - 1]
|
|
626
|
-
if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
|
|
627
|
-
if (plan.groupBy.length > 0) {
|
|
628
|
-
try {
|
|
629
|
-
api.setGroupBy(plan.groupBy)
|
|
630
|
-
} catch {
|
|
631
|
-
// grouping feature not enabled - the export still groups on its own
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
// Planning is always free; WRITING the file uses the export engine registered
|
|
637
|
-
// by @svgrid/enterprise (export-provider seam). Without it, we return the plan
|
|
638
|
-
// so the UI can still show what the AI decided - the download just no-ops.
|
|
639
|
-
const runExport = getExportProvider()
|
|
640
|
-
if (opts.run !== false && runExport) {
|
|
641
|
-
// Compute the export rows from the plan directly (filter + sort + make
|
|
642
|
-
// contiguous by group) rather than reading the grid's reactive displayed
|
|
643
|
-
// rows - so the download always has exactly the intended data.
|
|
644
|
-
const exportRows = applyPlanToRows(api.getData(), plan)
|
|
645
|
-
await runExport(api, {
|
|
646
|
-
format: plan.format,
|
|
647
|
-
filename: opts.filename ?? 'export',
|
|
648
|
-
rows: exportRows,
|
|
649
|
-
...(plan.groupBy.length > 0 ? { groupBy: plan.groupBy } : {}),
|
|
650
|
-
})
|
|
651
|
-
}
|
|
652
|
-
return plan
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
/** Evaluate one AI filter clause against a raw row value. */
|
|
656
|
-
function matchesClause(row: Record<string, unknown>, clause: AIFilterClause): boolean {
|
|
657
|
-
const v = row[clause.field]
|
|
658
|
-
const val = clause.value ?? ''
|
|
659
|
-
switch (clause.operator) {
|
|
660
|
-
case 'contains':
|
|
661
|
-
return String(v ?? '').toLowerCase().includes(val.toLowerCase())
|
|
662
|
-
case 'equals':
|
|
663
|
-
return String(v ?? '').toLowerCase() === val.toLowerCase()
|
|
664
|
-
case 'startsWith':
|
|
665
|
-
return String(v ?? '').toLowerCase().startsWith(val.toLowerCase())
|
|
666
|
-
case 'greaterThan':
|
|
667
|
-
return Number(v) > Number(val)
|
|
668
|
-
case 'lessThan':
|
|
669
|
-
return Number(v) < Number(val)
|
|
670
|
-
case 'isBlank':
|
|
671
|
-
return v == null || v === ''
|
|
672
|
-
default:
|
|
673
|
-
return true
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
/** Filter + sort + (stable) group the raw rows per an export plan. */
|
|
678
|
-
function applyPlanToRows<TData extends RowData>(
|
|
679
|
-
data: ReadonlyArray<TData>,
|
|
680
|
-
plan: AIExportPlan,
|
|
681
|
-
): TData[] {
|
|
682
|
-
let rows: TData[] = data.slice()
|
|
683
|
-
if (plan.filters.length > 0) {
|
|
684
|
-
rows = rows.filter((r) =>
|
|
685
|
-
plan.filters.every((f) => matchesClause(r as Record<string, unknown>, f)),
|
|
686
|
-
)
|
|
687
|
-
}
|
|
688
|
-
const last = plan.sort[plan.sort.length - 1]
|
|
689
|
-
if (last) {
|
|
690
|
-
rows = [...rows].sort((a, b) => {
|
|
691
|
-
const av = (a as Record<string, unknown>)[last.field]
|
|
692
|
-
const bv = (b as Record<string, unknown>)[last.field]
|
|
693
|
-
const na = Number(av)
|
|
694
|
-
const nb = Number(bv)
|
|
695
|
-
let cmp: number
|
|
696
|
-
if (Number.isFinite(na) && Number.isFinite(nb)) cmp = na - nb
|
|
697
|
-
else cmp = String(av ?? '').localeCompare(String(bv ?? ''))
|
|
698
|
-
return last.desc ? -cmp : cmp
|
|
699
|
-
})
|
|
700
|
-
}
|
|
701
|
-
// Contiguous grouping (first-seen order) so PDF group rows + Excel outline
|
|
702
|
-
// line up.
|
|
703
|
-
if (plan.groupBy.length > 0) {
|
|
704
|
-
const buckets = new Map<string, TData[]>()
|
|
705
|
-
for (const r of rows) {
|
|
706
|
-
const key = plan.groupBy
|
|
707
|
-
.map((k) => String((r as Record<string, unknown>)[k] ?? ''))
|
|
708
|
-
.join('')
|
|
709
|
-
const bucket = buckets.get(key)
|
|
710
|
-
if (bucket) bucket.push(r)
|
|
711
|
-
else buckets.set(key, [r])
|
|
712
|
-
}
|
|
713
|
-
rows = [...buckets.values()].flat()
|
|
714
|
-
}
|
|
715
|
-
return rows
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
// ---------------------------------------------------------------------------
|
|
719
|
-
// 6. Find anomalies
|
|
720
|
-
// ---------------------------------------------------------------------------
|
|
721
|
-
|
|
722
|
-
export type AIAnomaly = {
|
|
723
|
-
/** Index into the SCANNED rows (target order), when the model pins one row. */
|
|
724
|
-
rowIndex?: number
|
|
725
|
-
field?: string
|
|
726
|
-
value?: unknown
|
|
727
|
-
reason: string
|
|
728
|
-
severity: 'low' | 'medium' | 'high'
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
export type AIAnomalyResult = {
|
|
732
|
-
anomalies: AIAnomaly[]
|
|
733
|
-
summary: string
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
export type AIAnomalyOptions = {
|
|
737
|
-
/** Which rows to scan. Defaults to the whole dataset. */
|
|
738
|
-
target?: AISummarizeTarget
|
|
739
|
-
/** Optional focus, e.g. "look at pricing and margins". */
|
|
740
|
-
question?: string
|
|
741
|
-
signal?: AbortSignal
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
function sliceForTarget<TFeatures extends TableFeatures, TData extends RowData>(
|
|
745
|
-
api: SvGridApi<TFeatures, TData>,
|
|
746
|
-
target: AISummarizeTarget,
|
|
747
|
-
): TData[] {
|
|
748
|
-
const all = api.getData()
|
|
749
|
-
if (target.kind === 'row') {
|
|
750
|
-
const r = all[target.rowIndex]
|
|
751
|
-
return r ? [r] : []
|
|
752
|
-
}
|
|
753
|
-
if (target.kind === 'selection') {
|
|
754
|
-
return target.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
|
|
755
|
-
}
|
|
756
|
-
if (target.kind === 'group') {
|
|
757
|
-
return all.filter((r) => (r as Record<string, unknown>)[target.field] === target.value)
|
|
758
|
-
}
|
|
759
|
-
return all.slice()
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
/**
|
|
763
|
-
* Scan a slice of the grid (all / selection / group) for anomalies - outliers,
|
|
764
|
-
* suspicious values, inconsistencies - and return a structured list plus a
|
|
765
|
-
* one-line summary. Pairs naturally with an export: "find the odd ones, then
|
|
766
|
-
* export just those".
|
|
767
|
-
*/
|
|
768
|
-
export async function aiFindAnomalies<
|
|
769
|
-
TFeatures extends TableFeatures,
|
|
770
|
-
TData extends RowData,
|
|
771
|
-
>(
|
|
772
|
-
api: SvGridApi<TFeatures, TData>,
|
|
773
|
-
opts: AIAnomalyOptions = {},
|
|
774
|
-
): Promise<AIAnomalyResult> {
|
|
775
|
-
const rows = sliceForTarget(api, opts.target ?? { kind: 'all' })
|
|
776
|
-
if (rows.length === 0) return { anomalies: [], summary: 'No rows in scope.' }
|
|
777
|
-
|
|
778
|
-
const MAX_SAMPLE = 40
|
|
779
|
-
const sample =
|
|
780
|
-
rows.length <= MAX_SAMPLE
|
|
781
|
-
? rows
|
|
782
|
-
: Array.from(
|
|
783
|
-
{ length: MAX_SAMPLE },
|
|
784
|
-
(_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!,
|
|
785
|
-
)
|
|
786
|
-
|
|
787
|
-
const schema = buildColumnSchema(api, 30)
|
|
788
|
-
const prompt =
|
|
789
|
-
`You are a data-quality analyst. Scan the rows below for anomalies: ` +
|
|
790
|
-
`numeric outliers, impossible / inconsistent values, unexpected blanks, ` +
|
|
791
|
-
`and values that break the pattern of the column.\n\n` +
|
|
792
|
-
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
793
|
-
`Rows (index is 0-based into this list):\n` +
|
|
794
|
-
`${sample.map((r, i) => `${i}: ${JSON.stringify(r)}`).join('\n')}\n\n` +
|
|
795
|
-
(opts.question ? `Focus: ${opts.question}\n\n` : '') +
|
|
796
|
-
`Return strict JSON only:\n` +
|
|
797
|
-
`{ "anomalies": [{"rowIndex": <number|null>, "field": "<column|null>", ` +
|
|
798
|
-
`"reason": "<why it's odd>", "severity": "low"|"medium"|"high"}], ` +
|
|
799
|
-
`"summary": "<one sentence>" }`
|
|
800
|
-
|
|
801
|
-
const result = await callJSON<AIAnomalyResult>({
|
|
802
|
-
prompt,
|
|
803
|
-
task: 'anomaly',
|
|
804
|
-
signal: opts.signal,
|
|
805
|
-
maxOutputTokens: 800,
|
|
806
|
-
})
|
|
807
|
-
return {
|
|
808
|
-
anomalies: result.anomalies ?? [],
|
|
809
|
-
summary: result.summary ?? '',
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
// ---------------------------------------------------------------------------
|
|
814
|
-
// 7. Natural-language chart ("chart this")
|
|
815
|
-
// ---------------------------------------------------------------------------
|
|
816
|
-
|
|
817
|
-
export type AIChartType = 'bar' | 'line' | 'area' | 'pie'
|
|
818
|
-
|
|
819
|
-
export type AIChartPlan = {
|
|
820
|
-
type: AIChartType
|
|
821
|
-
/** Group-by (category-axis) column field, or null. */
|
|
822
|
-
dimension: string | null
|
|
823
|
-
/** Split-by column field: one series per distinct value, or null. */
|
|
824
|
-
series: string | null
|
|
825
|
-
/** Measure (value-axis) column field, or null. */
|
|
826
|
-
measure: string | null
|
|
827
|
-
reduce: 'sum' | 'avg' | 'count'
|
|
828
|
-
stacked: boolean
|
|
829
|
-
logScale: boolean
|
|
830
|
-
timeAxis: boolean
|
|
831
|
-
valueFormat: 'number' | 'currency' | 'percent'
|
|
832
|
-
rationale: string
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
export type AIChartOptions = {
|
|
836
|
-
/** Apply the plan to the grid's chart panel (open + configure). Default false. */
|
|
837
|
-
apply?: boolean
|
|
838
|
-
signal?: AbortSignal
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
/**
|
|
842
|
-
* Translate a natural-language request into a chart plan for the grid's built-in
|
|
843
|
-
* `charting` panel. Validates every field against the real schema, then (with
|
|
844
|
-
* `apply: true`) pushes it into the panel through `api.configureChart`.
|
|
845
|
-
*/
|
|
846
|
-
export async function aiChart<
|
|
847
|
-
TFeatures extends TableFeatures,
|
|
848
|
-
TData extends RowData,
|
|
849
|
-
>(
|
|
850
|
-
api: SvGridApi<TFeatures, TData>,
|
|
851
|
-
query: string,
|
|
852
|
-
opts: AIChartOptions = {},
|
|
853
|
-
): Promise<AIChartPlan> {
|
|
854
|
-
const schema = buildColumnSchema(api)
|
|
855
|
-
const prompt =
|
|
856
|
-
`You are a charting assistant for a data grid. Translate the user's request ` +
|
|
857
|
-
`into a strict-JSON chart plan the grid can render.\n\n` +
|
|
858
|
-
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
859
|
-
`Output JSON schema:\n` +
|
|
860
|
-
`{ "type": "bar"|"line"|"area"|"pie", ` +
|
|
861
|
-
`"dimension": "<a categorical column to group by>", ` +
|
|
862
|
-
`"series": "<a second categorical column to split into series, or null>", ` +
|
|
863
|
-
`"measure": "<a numeric column to aggregate>", ` +
|
|
864
|
-
`"reduce": "sum"|"avg"|"count", ` +
|
|
865
|
-
`"stacked": true|false, ` +
|
|
866
|
-
`"logScale": true|false, ` +
|
|
867
|
-
`"timeAxis": true|false, ` +
|
|
868
|
-
`"valueFormat": "number"|"currency"|"percent", ` +
|
|
869
|
-
`"rationale": "<one-sentence explanation>" }\n\n` +
|
|
870
|
-
`Rules: pick "dimension" and "series" from text/date columns and "measure" ` +
|
|
871
|
-
`from a numeric column; use only column names from the list above; ` +
|
|
872
|
-
`"stacked"/"stack" -> stacked:true; "log"/"logarithmic" -> logScale:true; ` +
|
|
873
|
-
`"over time"/"by date"/a date dimension -> timeAxis:true; ` +
|
|
874
|
-
`money/revenue/price/$ -> valueFormat:"currency"; rate/%/share -> valueFormat:"percent"; ` +
|
|
875
|
-
`else valueFormat:"number". default reduce is "sum". ` +
|
|
876
|
-
`Return JSON only, no prose.\n\n` +
|
|
877
|
-
`User request: ${query}`
|
|
878
|
-
|
|
879
|
-
const plan = await callJSON<AIChartPlan>({
|
|
880
|
-
prompt,
|
|
881
|
-
task: 'chart',
|
|
882
|
-
signal: opts.signal,
|
|
883
|
-
maxOutputTokens: 300,
|
|
884
|
-
})
|
|
885
|
-
|
|
886
|
-
const valid = new Set(schema.map((c) => c.field))
|
|
887
|
-
const numericFields = new Set(schema.filter((c) => c.type === 'number').map((c) => c.field))
|
|
888
|
-
const CHART_TYPES: AIChartType[] = ['bar', 'line', 'area', 'pie']
|
|
889
|
-
plan.type = CHART_TYPES.includes(plan.type) ? plan.type : 'bar'
|
|
890
|
-
plan.dimension = plan.dimension && valid.has(plan.dimension) ? plan.dimension : null
|
|
891
|
-
plan.series = plan.series && valid.has(plan.series) && plan.series !== plan.dimension ? plan.series : null
|
|
892
|
-
plan.measure =
|
|
893
|
-
plan.measure && numericFields.has(plan.measure)
|
|
894
|
-
? plan.measure
|
|
895
|
-
: (schema.find((c) => c.type === 'number')?.field ?? null)
|
|
896
|
-
plan.reduce = ['sum', 'avg', 'count'].includes(plan.reduce) ? plan.reduce : 'sum'
|
|
897
|
-
plan.stacked = plan.stacked === true
|
|
898
|
-
plan.logScale = plan.logScale === true
|
|
899
|
-
plan.timeAxis = plan.timeAxis === true
|
|
900
|
-
plan.valueFormat = ['number', 'currency', 'percent'].includes(plan.valueFormat) ? plan.valueFormat : 'number'
|
|
901
|
-
plan.rationale = plan.rationale ?? ''
|
|
902
|
-
|
|
903
|
-
if (opts.apply === true) {
|
|
904
|
-
const cfg = api as unknown as { configureChart?: (c: Record<string, unknown>) => void }
|
|
905
|
-
cfg.configureChart?.({
|
|
906
|
-
open: true,
|
|
907
|
-
type: plan.type,
|
|
908
|
-
dimension: plan.dimension,
|
|
909
|
-
series: plan.series,
|
|
910
|
-
measure: plan.measure,
|
|
911
|
-
reduce: plan.reduce,
|
|
912
|
-
stacked: plan.stacked,
|
|
913
|
-
logScale: plan.logScale,
|
|
914
|
-
timeAxis: plan.timeAxis,
|
|
915
|
-
valueFormat: plan.valueFormat,
|
|
916
|
-
})
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
return plan
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
/**
|
|
923
|
-
* Wire the grid's chart-panel AI button to the model: registers a handler (via
|
|
924
|
-
* `api.setChartAiHandler`) that runs `aiChart` and returns the plan for the
|
|
925
|
-
* panel to apply + explain. Call once after `onApiReady`. `installEnterprise`
|
|
926
|
-
* calls this for you.
|
|
927
|
-
*/
|
|
928
|
-
export function enableAiCharting<
|
|
929
|
-
TFeatures extends TableFeatures,
|
|
930
|
-
TData extends RowData,
|
|
931
|
-
>(api: SvGridApi<TFeatures, TData>): void {
|
|
932
|
-
const hook = api as unknown as {
|
|
933
|
-
setChartAiHandler?: (
|
|
934
|
-
fn: ((prompt: string) => Promise<Record<string, unknown> | null>) | null,
|
|
935
|
-
) => void
|
|
936
|
-
}
|
|
937
|
-
hook.setChartAiHandler?.(async (prompt: string) => {
|
|
938
|
-
const plan = await aiChart(api, prompt)
|
|
939
|
-
return {
|
|
940
|
-
type: plan.type,
|
|
941
|
-
dimension: plan.dimension,
|
|
942
|
-
series: plan.series,
|
|
943
|
-
measure: plan.measure,
|
|
944
|
-
reduce: plan.reduce,
|
|
945
|
-
stacked: plan.stacked,
|
|
946
|
-
logScale: plan.logScale,
|
|
947
|
-
timeAxis: plan.timeAxis,
|
|
948
|
-
valueFormat: plan.valueFormat,
|
|
949
|
-
rationale: plan.rationale,
|
|
950
|
-
}
|
|
951
|
-
})
|
|
952
|
-
}
|
|
953
|
-
|
|
954
|
-
export function disableAiCharting<
|
|
955
|
-
TFeatures extends TableFeatures,
|
|
956
|
-
TData extends RowData,
|
|
957
|
-
>(api: SvGridApi<TFeatures, TData>): void {
|
|
958
|
-
const hook = api as unknown as { setChartAiHandler?: (fn: null) => void }
|
|
959
|
-
hook.setChartAiHandler?.(null)
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
// ---------------------------------------------------------------------------
|
|
963
|
-
// 8. Mock provider for examples + tests
|
|
964
|
-
// ---------------------------------------------------------------------------
|
|
965
|
-
|
|
966
|
-
/**
|
|
967
|
-
* A deterministic provider that returns canned, schema-shaped responses
|
|
968
|
-
* for each task. Wire it in via `setAIProvider(mockAIProvider)` to make
|
|
969
|
-
* the AI demo work end-to-end without a real model key. Not for production.
|
|
970
|
-
*/
|
|
971
|
-
export const mockAIProvider: AIProvider = async (req) => {
|
|
972
|
-
// Tiny artificial delay so the UI's "thinking" state is visible.
|
|
973
|
-
await new Promise((r) => setTimeout(r, 350 + Math.random() * 400))
|
|
974
|
-
|
|
975
|
-
if (req.task === 'filter') {
|
|
976
|
-
const q = extractUserQuery(req.prompt)
|
|
977
|
-
return JSON.stringify(buildMockFilter(req.prompt, q))
|
|
978
|
-
}
|
|
979
|
-
if (req.task === 'smart-fill') {
|
|
980
|
-
return JSON.stringify(buildMockSmartFill(req.prompt))
|
|
981
|
-
}
|
|
982
|
-
if (req.task === 'summarize') {
|
|
983
|
-
return JSON.stringify(buildMockSummary(req.prompt))
|
|
984
|
-
}
|
|
985
|
-
if (req.task === 'classify') {
|
|
986
|
-
return JSON.stringify(buildMockClassify(req.prompt))
|
|
987
|
-
}
|
|
988
|
-
if (req.task === 'export') {
|
|
989
|
-
return JSON.stringify(buildMockExport(req.prompt))
|
|
990
|
-
}
|
|
991
|
-
if (req.task === 'anomaly') {
|
|
992
|
-
return JSON.stringify(buildMockAnomaly(req.prompt))
|
|
993
|
-
}
|
|
994
|
-
if (req.task === 'chart') {
|
|
995
|
-
return JSON.stringify(buildMockChart(req.prompt))
|
|
996
|
-
}
|
|
997
|
-
return '{}'
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
function buildMockChart(prompt: string): AIChartPlan {
|
|
1001
|
-
const q = extractUserRequest(prompt)
|
|
1002
|
-
const typed = extractFieldTypes(prompt)
|
|
1003
|
-
const textFields = typed.filter((f) => f.type === 'string' || f.type === 'date').map((f) => f.name)
|
|
1004
|
-
const numberFields = typed.filter((f) => f.type === 'number').map((f) => f.name)
|
|
1005
|
-
|
|
1006
|
-
const type: AIChartType =
|
|
1007
|
-
/\bline\b|\btrend\b|over time/.test(q) ? 'line'
|
|
1008
|
-
: /\barea\b/.test(q) ? 'area'
|
|
1009
|
-
: /\bpie\b|share|proportion|breakdown/.test(q) ? 'pie'
|
|
1010
|
-
: 'bar'
|
|
1011
|
-
|
|
1012
|
-
const byMatch = q.match(/\bby\s+([a-z0-9_ ]+?)(?:\s+(?:split|stacked|grouped|by|as|,|$))/)
|
|
1013
|
-
const pickText = (hint?: string): string | null => {
|
|
1014
|
-
if (hint) {
|
|
1015
|
-
const f = textFields.find((t) => t.toLowerCase() === hint.trim() || (hint.trim().length >= 4 && t.toLowerCase().includes(hint.trim())))
|
|
1016
|
-
if (f) return f
|
|
1017
|
-
}
|
|
1018
|
-
return null
|
|
1019
|
-
}
|
|
1020
|
-
const dimension = pickText(byMatch?.[1]) ?? textFields[0] ?? null
|
|
1021
|
-
const series =
|
|
1022
|
-
/\b(split|stack(?:ed)?|by product|by category|per)\b/.test(q)
|
|
1023
|
-
? (textFields.find((t) => t !== dimension) ?? null)
|
|
1024
|
-
: null
|
|
1025
|
-
const measure = numberFields.find((n) => q.includes(n.toLowerCase())) ?? numberFields[0] ?? null
|
|
1026
|
-
const reduce: 'sum' | 'avg' | 'count' =
|
|
1027
|
-
/\b(average|avg|mean)\b/.test(q) ? 'avg' : /\b(count|number of|how many)\b/.test(q) ? 'count' : 'sum'
|
|
1028
|
-
const stacked = /\bstack(ed)?\b/.test(q)
|
|
1029
|
-
const logScale = /\b(log|logarithmic)\b/.test(q)
|
|
1030
|
-
const timeAxis = /\b(over time|by date|by day|by month|by week|time series|timeline|trend)\b/.test(q)
|
|
1031
|
-
const valueFormat: 'number' | 'currency' | 'percent' =
|
|
1032
|
-
/\b(currency|money|revenue|sales|price|cost|\$|dollar)\b/.test(q) || /(price|revenue|amount|cost|sales)/i.test(measure ?? '')
|
|
1033
|
-
? 'currency'
|
|
1034
|
-
: /\b(percent|percentage|%|rate|share)\b/.test(q)
|
|
1035
|
-
? 'percent'
|
|
1036
|
-
: 'number'
|
|
1037
|
-
|
|
1038
|
-
return {
|
|
1039
|
-
type, dimension, series, measure, reduce, stacked, logScale, timeAxis, valueFormat,
|
|
1040
|
-
rationale:
|
|
1041
|
-
`${type} chart of ${reduce}(${measure ?? 'value'}) by ${dimension ?? 'category'}` +
|
|
1042
|
-
`${series ? `, split by ${series}` : ''}${stacked ? ', stacked' : ''}` +
|
|
1043
|
-
`${logScale ? ', log scale' : ''}${timeAxis ? ', date axis' : ''} (mock - wire a real model for genuine parsing).`,
|
|
1044
|
-
}
|
|
1045
|
-
}
|
|
1046
|
-
|
|
1047
|
-
function extractUserRequest(prompt: string): string {
|
|
1048
|
-
const m = prompt.match(/User request:\s*([\s\S]+)$/)
|
|
1049
|
-
return (m?.[1] ?? '').trim().toLowerCase()
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
function buildMockExport(prompt: string): AIExportPlan {
|
|
1053
|
-
const q = extractUserRequest(prompt)
|
|
1054
|
-
const fields = extractFields(prompt)
|
|
1055
|
-
// Reuse the filter mock (it reads "User query:"; feed it a compatible line).
|
|
1056
|
-
const filterPlan = buildMockFilter(prompt + `\nUser query: ${q}\n`, q)
|
|
1057
|
-
|
|
1058
|
-
// Format keyword routing.
|
|
1059
|
-
const format: ExportFormat =
|
|
1060
|
-
/\bpdf\b/.test(q) ? 'pdf'
|
|
1061
|
-
: /\bxls\b(?!x)/.test(q) || /97-2003|legacy excel/.test(q) ? 'xls'
|
|
1062
|
-
: /\b(xlsx|excel|spreadsheet|workbook)\b/.test(q) ? 'xlsx'
|
|
1063
|
-
: /\b(markdown|md)\b/.test(q) ? 'md'
|
|
1064
|
-
: /\bjson\b/.test(q) ? 'json'
|
|
1065
|
-
: /\bxml\b/.test(q) ? 'xml'
|
|
1066
|
-
: /\btsv\b/.test(q) ? 'tsv'
|
|
1067
|
-
: /\bhtml\b/.test(q) ? 'html'
|
|
1068
|
-
: /\bcsv\b/.test(q) ? 'csv'
|
|
1069
|
-
: 'xlsx'
|
|
1070
|
-
|
|
1071
|
-
// Grouping: "group by X" / "grouped by X", else "grouped" -> a categorical field.
|
|
1072
|
-
const groupBy: string[] = []
|
|
1073
|
-
const byMatch = q.match(/group(?:ed)?\s+by\s+([a-z0-9_ ,]+)/)
|
|
1074
|
-
if (byMatch) {
|
|
1075
|
-
for (const token of byMatch[1]!.split(/[, ]+/).filter(Boolean)) {
|
|
1076
|
-
// Exact field match, or a substring match only for tokens long enough to
|
|
1077
|
-
// be meaningful (so "a"/"as" don't match "amount").
|
|
1078
|
-
const f = fields.find(
|
|
1079
|
-
(ff) => ff.toLowerCase() === token || (token.length >= 4 && ff.toLowerCase().includes(token)),
|
|
1080
|
-
)
|
|
1081
|
-
if (f && !groupBy.includes(f)) groupBy.push(f)
|
|
1082
|
-
}
|
|
1083
|
-
} else if (/\bgroup(ed)?\b/.test(q)) {
|
|
1084
|
-
const cat = fields.find((f) => /region|country|category|status|stage|type|group|dept|team/i.test(f))
|
|
1085
|
-
if (cat) groupBy.push(cat)
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
return {
|
|
1089
|
-
format,
|
|
1090
|
-
filters: filterPlan.filters,
|
|
1091
|
-
sort: filterPlan.sort,
|
|
1092
|
-
groupBy,
|
|
1093
|
-
rationale: `Export as ${format}${groupBy.length ? `, grouped by ${groupBy.join(' / ')}` : ''}${filterPlan.filters.length ? `; ${filterPlan.rationale}` : ''}`,
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
function buildMockAnomaly(prompt: string): AIAnomalyResult {
|
|
1098
|
-
// Parse the sampled rows, flag the numeric outliers per numeric field.
|
|
1099
|
-
const rowsBlock = prompt.match(/Rows \(index is 0-based into this list\):\n([\s\S]*?)\n\n/)?.[1] ?? ''
|
|
1100
|
-
const parsed = rowsBlock
|
|
1101
|
-
.split('\n')
|
|
1102
|
-
.map((line) => {
|
|
1103
|
-
const m = line.match(/^(\d+):\s*(\{[\s\S]*\})$/)
|
|
1104
|
-
if (!m) return null
|
|
1105
|
-
const row = safeParse(m[2]!) as Record<string, unknown> | null
|
|
1106
|
-
return row ? { idx: parseInt(m[1]!, 10), row } : null
|
|
1107
|
-
})
|
|
1108
|
-
.filter((r): r is { idx: number; row: Record<string, unknown> } => !!r)
|
|
1109
|
-
|
|
1110
|
-
if (parsed.length === 0) {
|
|
1111
|
-
return { anomalies: [], summary: 'No rows to scan (mock).' }
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
// Genuinely numeric fields only: every value is null or a real number (so
|
|
1115
|
-
// booleans like `inStock` and id-ish strings are excluded). Also skip
|
|
1116
|
-
// identifier / row-index columns - a max "id" isn't an anomaly.
|
|
1117
|
-
const isIdLike = (f: string) => /(^id$|_id$|index|idx|^#|guid|uuid|serial|rownum)/i.test(f)
|
|
1118
|
-
const numericFields = Object.keys(parsed[0]!.row).filter(
|
|
1119
|
-
(f) =>
|
|
1120
|
-
!isIdLike(f) &&
|
|
1121
|
-
parsed.some((p) => typeof p.row[f] === 'number') &&
|
|
1122
|
-
parsed.every((p) => p.row[f] == null || typeof p.row[f] === 'number'),
|
|
1123
|
-
)
|
|
1124
|
-
|
|
1125
|
-
const anomalies: AIAnomaly[] = []
|
|
1126
|
-
for (const f of numericFields.slice(0, 2)) {
|
|
1127
|
-
let maxIdx = -1
|
|
1128
|
-
let maxVal = -Infinity
|
|
1129
|
-
for (const p of parsed) {
|
|
1130
|
-
const n = Number(p.row[f])
|
|
1131
|
-
if (Number.isFinite(n) && n > maxVal) {
|
|
1132
|
-
maxVal = n
|
|
1133
|
-
maxIdx = p.idx
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
if (maxIdx >= 0) {
|
|
1137
|
-
anomalies.push({
|
|
1138
|
-
rowIndex: maxIdx,
|
|
1139
|
-
field: f,
|
|
1140
|
-
value: maxVal,
|
|
1141
|
-
reason: `${f} = ${maxVal} is the highest in the sample and may be an outlier`,
|
|
1142
|
-
severity: 'medium',
|
|
1143
|
-
})
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
return {
|
|
1148
|
-
anomalies,
|
|
1149
|
-
summary:
|
|
1150
|
-
anomalies.length > 0
|
|
1151
|
-
? `Flagged ${anomalies.length} potential outlier${anomalies.length === 1 ? '' : 's'} (mock heuristic - wire a real model for genuine analysis).`
|
|
1152
|
-
: 'No obvious anomalies in the sample (mock).',
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
|
|
1156
|
-
function extractUserQuery(prompt: string): string {
|
|
1157
|
-
const m = prompt.match(/User query:\s*(.+?)\n/)
|
|
1158
|
-
return (m?.[1] ?? '').toLowerCase()
|
|
1159
|
-
}
|
|
1160
|
-
|
|
1161
|
-
function extractFields(prompt: string): string[] {
|
|
1162
|
-
const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
|
|
1163
|
-
if (!m) return []
|
|
1164
|
-
return (m[1] ?? '')
|
|
1165
|
-
.split('\n')
|
|
1166
|
-
.map((l) => l.match(/^- (\w+)/)?.[1])
|
|
1167
|
-
.filter((s): s is string => !!s)
|
|
1168
|
-
}
|
|
1169
|
-
|
|
1170
|
-
/** Parse the "- name (type): ..." schema block into {name, type} pairs. */
|
|
1171
|
-
function extractFieldTypes(prompt: string): Array<{ name: string; type: string }> {
|
|
1172
|
-
const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
|
|
1173
|
-
if (!m) return []
|
|
1174
|
-
return (m[1] ?? '')
|
|
1175
|
-
.split('\n')
|
|
1176
|
-
.map((l) => {
|
|
1177
|
-
const mm = l.match(/^- (\w+)\s*\((\w+)\)/)
|
|
1178
|
-
return mm ? { name: mm[1]!, type: mm[2]! } : null
|
|
1179
|
-
})
|
|
1180
|
-
.filter((x): x is { name: string; type: string } => !!x)
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
function buildMockFilter(prompt: string, q: string): AIFilterResult {
|
|
1184
|
-
const fields = extractFields(prompt)
|
|
1185
|
-
const filters: AIFilterClause[] = []
|
|
1186
|
-
const sort: AISortClause[] = []
|
|
1187
|
-
const rationale: string[] = []
|
|
1188
|
-
|
|
1189
|
-
// Greedy keyword routing. Real model would be smarter; this only needs
|
|
1190
|
-
// to convince the demo viewer the pipeline works.
|
|
1191
|
-
const numberWord = q.match(/(?:over|above|>|greater than)\s+\$?([\d.,]+)([kmb])?/)
|
|
1192
|
-
const lessWord = q.match(/(?:under|below|<|less than)\s+\$?([\d.,]+)([kmb])?/)
|
|
1193
|
-
// Pick a NUMBER-typed field (never a boolean like `inStock`), money-named
|
|
1194
|
-
// ones first so "$300" targets price/amount rather than a count/index.
|
|
1195
|
-
const numberTyped = extractFieldTypes(prompt).filter((f) => f.type === 'number').map((f) => f.name)
|
|
1196
|
-
const moneyRe = /(price|amount|cost|revenue|total|value|salary|arr|fee|spend|budget|sales)/i
|
|
1197
|
-
const numberPool = numberTyped.length > 0 ? numberTyped : fields
|
|
1198
|
-
const numberFields = [
|
|
1199
|
-
...numberPool.filter((f) => moneyRe.test(f)),
|
|
1200
|
-
...numberPool.filter((f) => !moneyRe.test(f)),
|
|
1201
|
-
]
|
|
1202
|
-
|
|
1203
|
-
if (numberWord && numberFields[0]) {
|
|
1204
|
-
const raw = parseFloat(numberWord[1]!.replace(/,/g, ''))
|
|
1205
|
-
const mul = numberWord[2] === 'k' ? 1_000 : numberWord[2] === 'm' ? 1_000_000 : numberWord[2] === 'b' ? 1_000_000_000 : 1
|
|
1206
|
-
filters.push({ field: numberFields[0], operator: 'greaterThan', value: String(raw * mul) })
|
|
1207
|
-
rationale.push(`amount > ${raw}${numberWord[2] ?? ''}`)
|
|
1208
|
-
} else if (lessWord && numberFields[0]) {
|
|
1209
|
-
const raw = parseFloat(lessWord[1]!.replace(/,/g, ''))
|
|
1210
|
-
const mul = lessWord[2] === 'k' ? 1_000 : lessWord[2] === 'm' ? 1_000_000 : 1
|
|
1211
|
-
filters.push({ field: numberFields[0], operator: 'lessThan', value: String(raw * mul) })
|
|
1212
|
-
rationale.push(`amount < ${raw}${lessWord[2] ?? ''}`)
|
|
1213
|
-
}
|
|
1214
|
-
|
|
1215
|
-
// Quoted phrases -> contains on a likely text field.
|
|
1216
|
-
const quote = q.match(/"([^"]+)"|'([^']+)'/)
|
|
1217
|
-
const textFields = fields.filter((f) => /(name|company|customer|title|owner|status|region|category|industry)/i.test(f))
|
|
1218
|
-
if (quote) {
|
|
1219
|
-
const term = quote[1] ?? quote[2] ?? ''
|
|
1220
|
-
if (textFields[0]) {
|
|
1221
|
-
filters.push({ field: textFields[0], operator: 'contains', value: term })
|
|
1222
|
-
rationale.push(`text contains "${term}"`)
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
// Person-name routing -> match owner/contact fields.
|
|
1227
|
-
const personOwners = ['sasha', 'jamie', 'casey', 'drew', 'robin', 'morgan', 'riley', 'quinn']
|
|
1228
|
-
for (const n of personOwners) {
|
|
1229
|
-
if (q.includes(n)) {
|
|
1230
|
-
const ownerField = fields.find((f) => /owner|rep|assigned/i.test(f)) ?? fields.find((f) => /name/i.test(f))
|
|
1231
|
-
if (ownerField) {
|
|
1232
|
-
filters.push({ field: ownerField, operator: 'contains', value: n })
|
|
1233
|
-
rationale.push(`owner ~ "${n}"`)
|
|
1234
|
-
break
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
// Region routing.
|
|
1240
|
-
for (const r of ['NA', 'EMEA', 'APAC', 'LATAM']) {
|
|
1241
|
-
if (q.toUpperCase().includes(r)) {
|
|
1242
|
-
const regionField = fields.find((f) => /region/i.test(f))
|
|
1243
|
-
if (regionField) {
|
|
1244
|
-
filters.push({ field: regionField, operator: 'equals', value: r })
|
|
1245
|
-
rationale.push(`region = ${r}`)
|
|
1246
|
-
break
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1251
|
-
// Status routing - any token in the query that matches a known status.
|
|
1252
|
-
for (const s of ['active', 'pending', 'won', 'lost', 'live', 'paused', 'shipped', 'delivered']) {
|
|
1253
|
-
if (q.includes(s)) {
|
|
1254
|
-
const f = fields.find((f) => /status|stage/i.test(f))
|
|
1255
|
-
if (f) {
|
|
1256
|
-
filters.push({ field: f, operator: 'equals', value: s })
|
|
1257
|
-
rationale.push(`status = ${s}`)
|
|
1258
|
-
break
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
|
|
1263
|
-
// Sort detection.
|
|
1264
|
-
if (/(highest|largest|biggest|top|most)/.test(q)) {
|
|
1265
|
-
const f = numberFields[0]
|
|
1266
|
-
if (f) { sort.push({ field: f, desc: true }); rationale.push(`sort by ${f} desc`) }
|
|
1267
|
-
} else if (/(lowest|smallest|least|cheapest)/.test(q)) {
|
|
1268
|
-
const f = numberFields[0]
|
|
1269
|
-
if (f) { sort.push({ field: f, desc: false }); rationale.push(`sort by ${f} asc`) }
|
|
1270
|
-
} else if (/(newest|recent|latest)/.test(q)) {
|
|
1271
|
-
const dateField = fields.find((f) => /date|at|time/i.test(f))
|
|
1272
|
-
if (dateField) { sort.push({ field: dateField, desc: true }); rationale.push(`sort by ${dateField} desc`) }
|
|
1273
|
-
} else if (/(oldest)/.test(q)) {
|
|
1274
|
-
const dateField = fields.find((f) => /date|at|time/i.test(f))
|
|
1275
|
-
if (dateField) { sort.push({ field: dateField, desc: false }); rationale.push(`sort by ${dateField} asc`) }
|
|
1276
|
-
}
|
|
1277
|
-
|
|
1278
|
-
return {
|
|
1279
|
-
filters,
|
|
1280
|
-
sort,
|
|
1281
|
-
rationale: rationale.length
|
|
1282
|
-
? `Interpreted: ${rationale.join(' AND ')}.`
|
|
1283
|
-
: `Couldn't identify a clear filter for "${q}". Showing all rows.`,
|
|
1284
|
-
}
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
function buildMockSmartFill(prompt: string): { predictions: Array<{ rowIndex: number; value: unknown; confidence: number }>; rationale: string } {
|
|
1288
|
-
// Extract the target column and the rows-to-fill block; copy the first
|
|
1289
|
-
// example's "output" pattern verbatim so the demo always returns
|
|
1290
|
-
// something believable. Real models do much better - that's the point.
|
|
1291
|
-
const fieldMatch = prompt.match(/Target column:\s*(\w+)/)
|
|
1292
|
-
const rowsMatch = prompt.match(/Rows to fill:\n([\s\S]*?)\n\n/)
|
|
1293
|
-
const exMatch = prompt.match(/Example 1: input=.* -> output=(.+)/)
|
|
1294
|
-
const targetField = fieldMatch?.[1] ?? ''
|
|
1295
|
-
const rowLines = (rowsMatch?.[1] ?? '').split('\n').filter(Boolean)
|
|
1296
|
-
const exampleOutput = exMatch?.[1] ? safeParse(exMatch[1]) : ''
|
|
1297
|
-
const predictions = rowLines
|
|
1298
|
-
.map((line) => {
|
|
1299
|
-
const m = line.match(/^Row (\d+): (\{.+\})/)
|
|
1300
|
-
if (!m) return null
|
|
1301
|
-
const rowIndex = parseInt(m[1]!, 10)
|
|
1302
|
-
const row = safeParse(m[2]!) as Record<string, unknown> | null
|
|
1303
|
-
if (!row) return null
|
|
1304
|
-
const value = inferFromRow(targetField, row, exampleOutput)
|
|
1305
|
-
return { rowIndex, value, confidence: 0.78 + Math.random() * 0.18 }
|
|
1306
|
-
})
|
|
1307
|
-
.filter((p): p is { rowIndex: number; value: unknown; confidence: number } => !!p)
|
|
1308
|
-
return {
|
|
1309
|
-
predictions,
|
|
1310
|
-
rationale: `Inferred from ${exMatch ? 'the supplied' : 'no'} examples; mocked deterministically for the demo.`,
|
|
1311
|
-
}
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
function safeParse(s: string): unknown {
|
|
1315
|
-
try { return JSON.parse(s) } catch { return null }
|
|
1316
|
-
}
|
|
1317
|
-
|
|
1318
|
-
function inferFromRow(field: string, row: Record<string, unknown>, exampleOutput: unknown): unknown {
|
|
1319
|
-
// Mock heuristics that produce a value that "looks right" in common
|
|
1320
|
-
// demo scenarios. The real provider would route through a real model.
|
|
1321
|
-
if (field === 'priority') {
|
|
1322
|
-
const arr = Number(row.arr ?? row.amount ?? row.price ?? 0)
|
|
1323
|
-
return arr > 100_000 ? 'high' : arr > 30_000 ? 'medium' : 'low'
|
|
1324
|
-
}
|
|
1325
|
-
if (field === 'tier') {
|
|
1326
|
-
const arr = Number(row.arr ?? row.amount ?? 0)
|
|
1327
|
-
return arr > 500_000 ? 'enterprise' : arr > 100_000 ? 'growth' : 'starter'
|
|
1328
|
-
}
|
|
1329
|
-
if (field === 'tags' || field === 'category') {
|
|
1330
|
-
return typeof exampleOutput === 'string' ? exampleOutput : 'auto-tag'
|
|
1331
|
-
}
|
|
1332
|
-
if (typeof exampleOutput === 'string') return exampleOutput
|
|
1333
|
-
if (typeof exampleOutput === 'number') return exampleOutput
|
|
1334
|
-
return exampleOutput ?? 'auto'
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
function buildMockSummary(prompt: string): AISummary {
|
|
1338
|
-
const sliceMatch = prompt.match(/Slice size: (\d+) row/)
|
|
1339
|
-
const n = sliceMatch ? parseInt(sliceMatch[1]!, 10) : 0
|
|
1340
|
-
const fields = extractSummaryFields(prompt)
|
|
1341
|
-
return {
|
|
1342
|
-
text:
|
|
1343
|
-
n === 1
|
|
1344
|
-
? `Single record. Notable signals come from ${fields.slice(0, 2).join(' and ') || 'the available fields'}.`
|
|
1345
|
-
: `${n} rows in scope. The distribution skews toward live / active records, with a long tail in ${fields[0] ?? 'amount'}.`,
|
|
1346
|
-
bullets: [
|
|
1347
|
-
`${n} row${n === 1 ? '' : 's'} sampled`,
|
|
1348
|
-
fields[0] ? `Largest variance in ${fields[0]}` : 'Tight clustering across visible fields',
|
|
1349
|
-
fields[1] ? `${fields[1]} concentrates around the median` : 'Few outliers',
|
|
1350
|
-
'Mock summary - wire setAIProvider() to a real model for actual analysis',
|
|
1351
|
-
],
|
|
1352
|
-
highlightedFields: fields.slice(0, 3),
|
|
1353
|
-
}
|
|
1354
|
-
}
|
|
1355
|
-
|
|
1356
|
-
function extractSummaryFields(prompt: string): string[] {
|
|
1357
|
-
const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
|
|
1358
|
-
if (!m) return []
|
|
1359
|
-
return (m[1] ?? '')
|
|
1360
|
-
.split('\n')
|
|
1361
|
-
.map((l) => l.match(/^- (\w+)/)?.[1])
|
|
1362
|
-
.filter((s): s is string => !!s)
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
|
-
function buildMockClassify(prompt: string): { predictions: Array<{ rowIndex: number; value: string; confidence: number }> } {
|
|
1366
|
-
const labelsMatch = prompt.match(/Allowed labels[\s\S]*?:\n([\s\S]*?)\n\n/)
|
|
1367
|
-
// Capture the label up to the first colon, whitespace or end-of-line so
|
|
1368
|
-
// we don't pick up the rubric ("- at-risk: churn signals..." -> "at-risk").
|
|
1369
|
-
const labels = (labelsMatch?.[1] ?? '')
|
|
1370
|
-
.split('\n')
|
|
1371
|
-
.map((l) => l.match(/^-\s*([^\s:]+)/)?.[1])
|
|
1372
|
-
.filter((s): s is string => !!s)
|
|
1373
|
-
const rowLines = (prompt.match(/Rows to classify[\s\S]*?:\n([\s\S]*?)\n\n/)?.[1] ?? '').split('\n').filter(Boolean)
|
|
1374
|
-
const predictions = rowLines.map((line) => {
|
|
1375
|
-
const m = line.match(/^Row (\d+): "(.*)"/)
|
|
1376
|
-
if (!m || labels.length === 0) return null
|
|
1377
|
-
const rowIndex = parseInt(m[1]!, 10)
|
|
1378
|
-
const text = (m[2] ?? '').toLowerCase()
|
|
1379
|
-
// Pick the label whose token appears in the text; otherwise hash.
|
|
1380
|
-
const hit = labels.find((l) => text.includes(l.toLowerCase()))
|
|
1381
|
-
const value = hit ?? labels[Math.abs(hashStr(text)) % labels.length]!
|
|
1382
|
-
return { rowIndex, value, confidence: hit ? 0.92 : 0.6 + Math.random() * 0.2 }
|
|
1383
|
-
}).filter((p): p is { rowIndex: number; value: string; confidence: number } => !!p)
|
|
1384
|
-
return { predictions }
|
|
1385
|
-
}
|
|
1386
|
-
|
|
1387
|
-
function hashStr(s: string): number {
|
|
1388
|
-
let h = 0
|
|
1389
|
-
for (let i = 0; i < s.length; i += 1) h = (h * 31 + s.charCodeAt(i)) | 0
|
|
1390
|
-
return h
|
|
1391
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Pro AI feature pack
|
|
3
|
+
* -------------------
|
|
4
|
+
*
|
|
5
|
+
* Three jobs every analyst wishes a data grid could do:
|
|
6
|
+
*
|
|
7
|
+
* 1. Natural-language filter / sort (`aiFilter`)
|
|
8
|
+
* "show me deals closing this quarter over $50k owned by Sasha"
|
|
9
|
+
* -> { filters: [...], sort: [...] }
|
|
10
|
+
*
|
|
11
|
+
* 2. Smart fill (`aiSmartFill`)
|
|
12
|
+
* User edits two cells in a column with example values; the
|
|
13
|
+
* Grid proposes the rest. Excel "Flash Fill" pattern.
|
|
14
|
+
*
|
|
15
|
+
* 3. Summarise rows (`aiSummarize`)
|
|
16
|
+
* Single row, the current selection, a group key, or the whole
|
|
17
|
+
* filtered view -> a one-paragraph summary.
|
|
18
|
+
*
|
|
19
|
+
* The grid stays headless / model-agnostic. The consumer supplies an
|
|
20
|
+
* `AIProvider` that knows how to call OpenAI / Anthropic / a local
|
|
21
|
+
* model / a server-side proxy. We never bundle a model client.
|
|
22
|
+
*
|
|
23
|
+
* Built-in + free: the AI helpers live in `@svgrid/grid`. They ship no model
|
|
24
|
+
* client and do nothing until you register a provider with `setAIProvider(...)`,
|
|
25
|
+
* so they add nothing to the base bundle unless you actually use them.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type { RowData, SvGridApi, TableFeatures } from './index'
|
|
29
|
+
import { getExportProvider } from './export-provider'
|
|
30
|
+
|
|
31
|
+
// Export formats an AI export can plan. WRITING the enterprise formats (xlsx /
|
|
32
|
+
// pdf / html / xml / md) needs the export engine from `@svgrid/enterprise`
|
|
33
|
+
// (registered via the export-provider seam); csv / tsv / json are also handled
|
|
34
|
+
// by that engine when present. The union is declared locally so the free grid
|
|
35
|
+
// carries no dependency on the enterprise export module.
|
|
36
|
+
type ExportFormat = 'xlsx' | 'xls' | 'pdf' | 'csv' | 'tsv' | 'html' | 'json' | 'xml' | 'md'
|
|
37
|
+
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
// Provider contract
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Shape every consumer-provided model adapter must implement. Keeping this
|
|
44
|
+
* tiny (one async call, two response formats) lets the same adapter drive
|
|
45
|
+
* OpenAI's `chat.completions`, Anthropic's `messages`, a self-hosted
|
|
46
|
+
* llama.cpp endpoint, or a server-side proxy. The grid only cares that the
|
|
47
|
+
* provider eventually returns a string we can parse.
|
|
48
|
+
*/
|
|
49
|
+
export type AIProvider = (request: AIRequest) => Promise<string>
|
|
50
|
+
|
|
51
|
+
export type AIRequest = {
|
|
52
|
+
/** Full prompt the grid built for the model. Already includes column
|
|
53
|
+
* schema and any sampled rows where applicable. */
|
|
54
|
+
prompt: string
|
|
55
|
+
/** When 'json', the provider should ask the model to return strict
|
|
56
|
+
* JSON only - no prose. We parse the response with JSON.parse and
|
|
57
|
+
* throw a typed error on failure. */
|
|
58
|
+
responseFormat?: 'text' | 'json'
|
|
59
|
+
/** Honored if the underlying transport supports cancellation. */
|
|
60
|
+
signal?: AbortSignal
|
|
61
|
+
/** Free-form tag for telemetry / logging. One of: 'filter',
|
|
62
|
+
* 'smart-fill', 'summarize', 'classify'. */
|
|
63
|
+
task: AITask
|
|
64
|
+
/** Soft hint to the provider about how many tokens we expect back.
|
|
65
|
+
* Useful for routing small jobs to a cheaper model. */
|
|
66
|
+
maxOutputTokens?: number
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type AITask = 'filter' | 'smart-fill' | 'summarize' | 'classify' | 'export' | 'anomaly' | 'chart'
|
|
70
|
+
|
|
71
|
+
let provider: AIProvider | null = null
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Register the model adapter every AI call will route through. Call once
|
|
75
|
+
* at app boot. Passing `null` clears the provider and AI calls revert to
|
|
76
|
+
* throwing "no provider" errors.
|
|
77
|
+
*/
|
|
78
|
+
export function setAIProvider(p: AIProvider | null): void {
|
|
79
|
+
provider = p
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function getAIProvider(): AIProvider | null {
|
|
83
|
+
return provider
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function hasAIProvider(): boolean {
|
|
87
|
+
return provider != null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
class NoProviderError extends Error {
|
|
91
|
+
constructor() {
|
|
92
|
+
super(
|
|
93
|
+
'@svgrid/grid ai: no AI provider registered. Call setAIProvider(fn) ' +
|
|
94
|
+
'with an adapter that talks to OpenAI / Anthropic / your proxy.',
|
|
95
|
+
)
|
|
96
|
+
this.name = 'NoProviderError'
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
class BadJsonError extends Error {
|
|
101
|
+
constructor(raw: string) {
|
|
102
|
+
super(
|
|
103
|
+
'@svgrid/grid ai: provider returned non-JSON for a json-format request. ' +
|
|
104
|
+
`First 200 chars: ${raw.slice(0, 200)}`,
|
|
105
|
+
)
|
|
106
|
+
this.name = 'BadJsonError'
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function callProvider(req: AIRequest): Promise<string> {
|
|
111
|
+
if (!provider) throw new NoProviderError()
|
|
112
|
+
return provider(req)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function callJSON<T>(req: AIRequest): Promise<T> {
|
|
116
|
+
const raw = await callProvider({ ...req, responseFormat: 'json' })
|
|
117
|
+
// Models occasionally wrap JSON in markdown code fences even when asked
|
|
118
|
+
// for raw JSON. Strip a single fenced block if present, then parse.
|
|
119
|
+
const stripped = raw.trim().replace(/^```(?:json)?\s*|\s*```$/g, '')
|
|
120
|
+
try {
|
|
121
|
+
return JSON.parse(stripped) as T
|
|
122
|
+
} catch {
|
|
123
|
+
throw new BadJsonError(raw)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// Helpers - build column schema + row sample from the grid API
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
type ColumnSchemaEntry = {
|
|
132
|
+
field: string
|
|
133
|
+
type: 'string' | 'number' | 'boolean' | 'date' | 'unknown'
|
|
134
|
+
sampleValues: unknown[]
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Inspect the first N rows the grid is holding to infer a typed schema +
|
|
139
|
+
* a handful of sample values per column. This is the context every AI
|
|
140
|
+
* task needs and the most expensive thing to build, so the helpers cache
|
|
141
|
+
* the result inside one task call rather than calling api.getData()
|
|
142
|
+
* repeatedly.
|
|
143
|
+
*/
|
|
144
|
+
function buildColumnSchema<
|
|
145
|
+
TFeatures extends TableFeatures,
|
|
146
|
+
TData extends RowData,
|
|
147
|
+
>(api: SvGridApi<TFeatures, TData>, sampleSize = 50): ColumnSchemaEntry[] {
|
|
148
|
+
const data = api.getData()
|
|
149
|
+
if (data.length === 0) return []
|
|
150
|
+
const slice = data.slice(0, Math.min(data.length, sampleSize))
|
|
151
|
+
const fields = new Set<string>()
|
|
152
|
+
for (const row of slice) {
|
|
153
|
+
for (const k of Object.keys(row as object)) fields.add(k)
|
|
154
|
+
}
|
|
155
|
+
const out: ColumnSchemaEntry[] = []
|
|
156
|
+
for (const field of fields) {
|
|
157
|
+
const values: unknown[] = []
|
|
158
|
+
for (const row of slice) {
|
|
159
|
+
const v = (row as Record<string, unknown>)[field]
|
|
160
|
+
if (v != null) values.push(v)
|
|
161
|
+
if (values.length >= 5) break
|
|
162
|
+
}
|
|
163
|
+
out.push({
|
|
164
|
+
field,
|
|
165
|
+
type: inferType(values),
|
|
166
|
+
sampleValues: values,
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
return out
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function inferType(samples: unknown[]): ColumnSchemaEntry['type'] {
|
|
173
|
+
if (samples.length === 0) return 'unknown'
|
|
174
|
+
const v = samples[0]
|
|
175
|
+
if (typeof v === 'number') return 'number'
|
|
176
|
+
if (typeof v === 'boolean') return 'boolean'
|
|
177
|
+
if (typeof v === 'string') {
|
|
178
|
+
// Cheap ISO-date sniff so we route date-style filters correctly.
|
|
179
|
+
if (/^\d{4}-\d{2}-\d{2}/.test(v)) return 'date'
|
|
180
|
+
return 'string'
|
|
181
|
+
}
|
|
182
|
+
return 'unknown'
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function schemaToPromptBlock(schema: ColumnSchemaEntry[]): string {
|
|
186
|
+
return schema
|
|
187
|
+
.map(
|
|
188
|
+
(c) =>
|
|
189
|
+
`- ${c.field} (${c.type}): e.g. ${c.sampleValues
|
|
190
|
+
.slice(0, 3)
|
|
191
|
+
.map((v) => JSON.stringify(v))
|
|
192
|
+
.join(', ')}`,
|
|
193
|
+
)
|
|
194
|
+
.join('\n')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
// 1. Natural-language filter / sort
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
export type AIFilterClause = {
|
|
202
|
+
field: string
|
|
203
|
+
operator: 'contains' | 'equals' | 'startsWith' | 'greaterThan' | 'lessThan' | 'isBlank'
|
|
204
|
+
value?: string
|
|
205
|
+
}
|
|
206
|
+
export type AISortClause = { field: string; desc: boolean }
|
|
207
|
+
|
|
208
|
+
export type AIFilterResult = {
|
|
209
|
+
filters: AIFilterClause[]
|
|
210
|
+
sort: AISortClause[]
|
|
211
|
+
/** Plain-English explanation of how the model interpreted the query.
|
|
212
|
+
* Surface this in the UI so the user can confirm or undo. */
|
|
213
|
+
rationale: string
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export type AIFilterOptions = {
|
|
217
|
+
/**
|
|
218
|
+
* When true, the helper not only RETURNS the plan but also applies it
|
|
219
|
+
* to the grid via `api.setFilter` / `api.setSort`. Defaults to false
|
|
220
|
+
* so callers can show a preview before committing.
|
|
221
|
+
*/
|
|
222
|
+
apply?: boolean
|
|
223
|
+
signal?: AbortSignal
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Translate a natural-language query into a filter+sort plan against
|
|
228
|
+
* the current grid's columns. The grid passes the column schema (names,
|
|
229
|
+
* types, sample values) to the model so it can pick the right field
|
|
230
|
+
* names without hallucinating.
|
|
231
|
+
*/
|
|
232
|
+
export async function aiFilter<
|
|
233
|
+
TFeatures extends TableFeatures,
|
|
234
|
+
TData extends RowData,
|
|
235
|
+
>(
|
|
236
|
+
api: SvGridApi<TFeatures, TData>,
|
|
237
|
+
query: string,
|
|
238
|
+
opts: AIFilterOptions = {},
|
|
239
|
+
): Promise<AIFilterResult> {
|
|
240
|
+
const schema = buildColumnSchema(api)
|
|
241
|
+
const prompt =
|
|
242
|
+
`You are a data-grid filter planner. Translate the user's natural-language ` +
|
|
243
|
+
`query into a strict-JSON plan that the grid can apply.\n\n` +
|
|
244
|
+
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
245
|
+
`Output JSON schema:\n` +
|
|
246
|
+
`{ "filters": [{"field": "<one of the columns above>", ` +
|
|
247
|
+
`"operator": "contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank", ` +
|
|
248
|
+
`"value": "<string>"}], ` +
|
|
249
|
+
`"sort": [{"field": "<column>", "desc": true|false}], ` +
|
|
250
|
+
`"rationale": "<one-sentence explanation>" }\n\n` +
|
|
251
|
+
`User query: ${query}\n\n` +
|
|
252
|
+
`Return JSON only, no prose.`
|
|
253
|
+
|
|
254
|
+
const result = await callJSON<AIFilterResult>({
|
|
255
|
+
prompt,
|
|
256
|
+
task: 'filter',
|
|
257
|
+
signal: opts.signal,
|
|
258
|
+
maxOutputTokens: 400,
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
// Defensive: drop anything that doesn't match a real column. Models love
|
|
262
|
+
// to invent plausible-sounding field names; we'd rather skip a clause
|
|
263
|
+
// than throw at runtime.
|
|
264
|
+
const valid = new Set(schema.map((c) => c.field))
|
|
265
|
+
result.filters = (result.filters ?? []).filter((f) => valid.has(f.field))
|
|
266
|
+
result.sort = (result.sort ?? []).filter((s) => valid.has(s.field))
|
|
267
|
+
|
|
268
|
+
if (opts.apply) {
|
|
269
|
+
api.clearAllFilters()
|
|
270
|
+
api.clearSort()
|
|
271
|
+
for (const f of result.filters) {
|
|
272
|
+
api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
|
|
273
|
+
}
|
|
274
|
+
// Multiple sort clauses get applied last-wins because the public
|
|
275
|
+
// `setSort` is single-key. Multi-sort is on the roadmap.
|
|
276
|
+
const last = result.sort[result.sort.length - 1]
|
|
277
|
+
if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return result
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ---------------------------------------------------------------------------
|
|
284
|
+
// 2. Smart fill
|
|
285
|
+
// ---------------------------------------------------------------------------
|
|
286
|
+
|
|
287
|
+
export type AISmartFillExample = { input: Record<string, unknown>; output: unknown }
|
|
288
|
+
|
|
289
|
+
export type AISmartFillResult<TValue = unknown> = {
|
|
290
|
+
field: string
|
|
291
|
+
predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
|
|
292
|
+
rationale: string
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export type AISmartFillOptions = {
|
|
296
|
+
/** Target column - the one whose values we want filled. */
|
|
297
|
+
field: string
|
|
298
|
+
/** Index of rows the model should propose values for. If omitted, every
|
|
299
|
+
* row whose current `field` value is `null`, `undefined` or `''` is
|
|
300
|
+
* selected automatically. */
|
|
301
|
+
targetRowIndices?: number[]
|
|
302
|
+
/**
|
|
303
|
+
* Worked examples the user has already filled in. Required - the
|
|
304
|
+
* model needs at least one to know the pattern, two or more to lock
|
|
305
|
+
* the schema. We don't pull these from the grid automatically because
|
|
306
|
+
* "edited" vs "untouched" isn't a state SvGrid exposes today.
|
|
307
|
+
*/
|
|
308
|
+
examples: AISmartFillExample[]
|
|
309
|
+
signal?: AbortSignal
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Given a column and a few user-provided examples, propose values for the
|
|
314
|
+
* untouched rows. Returns predictions only - the caller chooses whether to
|
|
315
|
+
* commit them via `api.setCellValue`. This is the right shape for an
|
|
316
|
+
* accept-per-cell UX with confidence-coloured highlights.
|
|
317
|
+
*/
|
|
318
|
+
export async function aiSmartFill<
|
|
319
|
+
TFeatures extends TableFeatures,
|
|
320
|
+
TData extends RowData,
|
|
321
|
+
TValue = unknown,
|
|
322
|
+
>(
|
|
323
|
+
api: SvGridApi<TFeatures, TData>,
|
|
324
|
+
opts: AISmartFillOptions,
|
|
325
|
+
): Promise<AISmartFillResult<TValue>> {
|
|
326
|
+
if (opts.examples.length === 0) {
|
|
327
|
+
throw new Error('@svgrid/grid ai: aiSmartFill requires at least one example.')
|
|
328
|
+
}
|
|
329
|
+
const data = api.getData()
|
|
330
|
+
const targets =
|
|
331
|
+
opts.targetRowIndices ??
|
|
332
|
+
data
|
|
333
|
+
.map((row, i) => {
|
|
334
|
+
const v = (row as Record<string, unknown>)[opts.field]
|
|
335
|
+
return v == null || v === '' ? i : -1
|
|
336
|
+
})
|
|
337
|
+
.filter((i) => i >= 0)
|
|
338
|
+
|
|
339
|
+
if (targets.length === 0) {
|
|
340
|
+
return { field: opts.field, predictions: [], rationale: 'No empty cells to fill.' }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const examplesBlock = opts.examples
|
|
344
|
+
.map((ex, i) => `Example ${i + 1}: input=${JSON.stringify(ex.input)} -> output=${JSON.stringify(ex.output)}`)
|
|
345
|
+
.join('\n')
|
|
346
|
+
|
|
347
|
+
const targetRowsBlock = targets
|
|
348
|
+
.map((i) => `Row ${i}: ${JSON.stringify(data[i])}`)
|
|
349
|
+
.join('\n')
|
|
350
|
+
|
|
351
|
+
const prompt =
|
|
352
|
+
`You are filling in a single column of a data grid based on user-provided ` +
|
|
353
|
+
`examples. Match the pattern in the examples exactly.\n\n` +
|
|
354
|
+
`Target column: ${opts.field}\n\n` +
|
|
355
|
+
`Examples:\n${examplesBlock}\n\n` +
|
|
356
|
+
`Rows to fill:\n${targetRowsBlock}\n\n` +
|
|
357
|
+
`Return strict JSON only:\n` +
|
|
358
|
+
`{ "predictions": [{"rowIndex": <number>, "value": <inferred value>, ` +
|
|
359
|
+
`"confidence": <0..1>}], "rationale": "<one-sentence pattern description>" }`
|
|
360
|
+
|
|
361
|
+
const result = await callJSON<{
|
|
362
|
+
predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>
|
|
363
|
+
rationale: string
|
|
364
|
+
}>({
|
|
365
|
+
prompt,
|
|
366
|
+
task: 'smart-fill',
|
|
367
|
+
signal: opts.signal,
|
|
368
|
+
maxOutputTokens: 600,
|
|
369
|
+
})
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
field: opts.field,
|
|
373
|
+
predictions: result.predictions ?? [],
|
|
374
|
+
rationale: result.rationale ?? '',
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ---------------------------------------------------------------------------
|
|
379
|
+
// 3. Summarise
|
|
380
|
+
// ---------------------------------------------------------------------------
|
|
381
|
+
|
|
382
|
+
export type AISummarizeTarget =
|
|
383
|
+
| { kind: 'row'; rowIndex: number }
|
|
384
|
+
| { kind: 'all' }
|
|
385
|
+
| { kind: 'selection'; rowIndices: number[] }
|
|
386
|
+
| { kind: 'group'; field: string; value: unknown }
|
|
387
|
+
|
|
388
|
+
export type AISummary = {
|
|
389
|
+
text: string
|
|
390
|
+
bullets: string[]
|
|
391
|
+
/** Field names the model thinks are the most load-bearing for the
|
|
392
|
+
* story it just told. UI can highlight those columns. */
|
|
393
|
+
highlightedFields: string[]
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export type AISummarizeOptions = {
|
|
397
|
+
target: AISummarizeTarget
|
|
398
|
+
/** Optional question the user is trying to answer. Helps the model
|
|
399
|
+
* bias the summary toward the relevant columns. */
|
|
400
|
+
question?: string
|
|
401
|
+
signal?: AbortSignal
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Ask the model to summarise a slice of the grid. Caps the row sample at
|
|
406
|
+
* a model-friendly size; for huge selections it samples uniformly so the
|
|
407
|
+
* summary stays representative without blowing the context window.
|
|
408
|
+
*/
|
|
409
|
+
export async function aiSummarize<
|
|
410
|
+
TFeatures extends TableFeatures,
|
|
411
|
+
TData extends RowData,
|
|
412
|
+
>(
|
|
413
|
+
api: SvGridApi<TFeatures, TData>,
|
|
414
|
+
opts: AISummarizeOptions,
|
|
415
|
+
): Promise<AISummary> {
|
|
416
|
+
const all = api.getData()
|
|
417
|
+
const rows: TData[] = (() => {
|
|
418
|
+
const t = opts.target
|
|
419
|
+
if (t.kind === 'row') {
|
|
420
|
+
const r = all[t.rowIndex]
|
|
421
|
+
return r ? [r] : []
|
|
422
|
+
}
|
|
423
|
+
if (t.kind === 'selection') {
|
|
424
|
+
return t.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
|
|
425
|
+
}
|
|
426
|
+
if (t.kind === 'group') {
|
|
427
|
+
return all.filter((r) => (r as Record<string, unknown>)[t.field] === t.value)
|
|
428
|
+
}
|
|
429
|
+
return all.slice()
|
|
430
|
+
})()
|
|
431
|
+
|
|
432
|
+
if (rows.length === 0) {
|
|
433
|
+
return { text: 'No rows in scope.', bullets: [], highlightedFields: [] }
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// Uniform sample to stay inside a sensible context budget.
|
|
437
|
+
const MAX_SAMPLE = 25
|
|
438
|
+
const sample = rows.length <= MAX_SAMPLE
|
|
439
|
+
? rows
|
|
440
|
+
: Array.from({ length: MAX_SAMPLE }, (_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!)
|
|
441
|
+
|
|
442
|
+
const schema = buildColumnSchema(api, 30)
|
|
443
|
+
const prompt =
|
|
444
|
+
`You are summarising a slice of a business data grid for a busy analyst.\n\n` +
|
|
445
|
+
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
446
|
+
`Slice size: ${rows.length} row(s). Sampled rows shown below.\n` +
|
|
447
|
+
`${sample.map((r) => JSON.stringify(r)).join('\n')}\n\n` +
|
|
448
|
+
(opts.question ? `User's question: ${opts.question}\n\n` : '') +
|
|
449
|
+
`Return strict JSON only:\n` +
|
|
450
|
+
`{ "text": "<one short paragraph>", ` +
|
|
451
|
+
`"bullets": ["<3-5 punchy bullets>"], ` +
|
|
452
|
+
`"highlightedFields": ["<column names the summary leans on>"] }`
|
|
453
|
+
|
|
454
|
+
const result = await callJSON<AISummary>({
|
|
455
|
+
prompt,
|
|
456
|
+
task: 'summarize',
|
|
457
|
+
signal: opts.signal,
|
|
458
|
+
maxOutputTokens: 600,
|
|
459
|
+
})
|
|
460
|
+
return {
|
|
461
|
+
text: result.text ?? '',
|
|
462
|
+
bullets: result.bullets ?? [],
|
|
463
|
+
highlightedFields: result.highlightedFields ?? [],
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// ---------------------------------------------------------------------------
|
|
468
|
+
// 4. Classify (free-text -> bucketed value)
|
|
469
|
+
// ---------------------------------------------------------------------------
|
|
470
|
+
|
|
471
|
+
export type AIClassifyOptions = {
|
|
472
|
+
/** Column whose free-text we're classifying. */
|
|
473
|
+
inputField: string
|
|
474
|
+
/** Target column the model should write to. */
|
|
475
|
+
outputField: string
|
|
476
|
+
/** Allowed values. The model is constrained to pick one. */
|
|
477
|
+
classes: string[]
|
|
478
|
+
/** Optional one-line description of each class (acts as a labeling rubric). */
|
|
479
|
+
classDescriptions?: Record<string, string>
|
|
480
|
+
/** Rows to classify. Defaults to all. */
|
|
481
|
+
targetRowIndices?: number[]
|
|
482
|
+
signal?: AbortSignal
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export type AIClassifyResult = {
|
|
486
|
+
inputField: string
|
|
487
|
+
outputField: string
|
|
488
|
+
predictions: Array<{ rowIndex: number; value: string; confidence: number }>
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Bucket free-text cells into one of a known set of classes. The model
|
|
493
|
+
* is constrained to pick from `opts.classes`; predictions outside the set
|
|
494
|
+
* are dropped so the caller can rely on the output being clean enum
|
|
495
|
+
* values it can write straight back into the grid.
|
|
496
|
+
*/
|
|
497
|
+
export async function aiClassify<
|
|
498
|
+
TFeatures extends TableFeatures,
|
|
499
|
+
TData extends RowData,
|
|
500
|
+
>(
|
|
501
|
+
api: SvGridApi<TFeatures, TData>,
|
|
502
|
+
opts: AIClassifyOptions,
|
|
503
|
+
): Promise<AIClassifyResult> {
|
|
504
|
+
const data = api.getData()
|
|
505
|
+
const targets = opts.targetRowIndices ?? data.map((_, i) => i)
|
|
506
|
+
const rubric = opts.classDescriptions
|
|
507
|
+
? Object.entries(opts.classDescriptions)
|
|
508
|
+
.map(([k, v]) => `- ${k}: ${v}`)
|
|
509
|
+
.join('\n')
|
|
510
|
+
: opts.classes.map((c) => `- ${c}`).join('\n')
|
|
511
|
+
|
|
512
|
+
const rowsBlock = targets
|
|
513
|
+
.map((i) => `Row ${i}: ${JSON.stringify((data[i] as Record<string, unknown>)?.[opts.inputField] ?? '')}`)
|
|
514
|
+
.join('\n')
|
|
515
|
+
|
|
516
|
+
const prompt =
|
|
517
|
+
`You are a strict text classifier. For each row, pick exactly one ` +
|
|
518
|
+
`label from the list. If unsure, pick the closest match and lower the ` +
|
|
519
|
+
`confidence.\n\n` +
|
|
520
|
+
`Allowed labels (with optional rubric):\n${rubric}\n\n` +
|
|
521
|
+
`Rows to classify (text from column "${opts.inputField}"):\n${rowsBlock}\n\n` +
|
|
522
|
+
`Return strict JSON only:\n` +
|
|
523
|
+
`{ "predictions": [{"rowIndex": <number>, "value": "<label>", "confidence": <0..1>}] }`
|
|
524
|
+
|
|
525
|
+
const result = await callJSON<{
|
|
526
|
+
predictions: Array<{ rowIndex: number; value: string; confidence: number }>
|
|
527
|
+
}>({
|
|
528
|
+
prompt,
|
|
529
|
+
task: 'classify',
|
|
530
|
+
signal: opts.signal,
|
|
531
|
+
maxOutputTokens: Math.min(2000, 30 + targets.length * 30),
|
|
532
|
+
})
|
|
533
|
+
|
|
534
|
+
const allowed = new Set(opts.classes)
|
|
535
|
+
return {
|
|
536
|
+
inputField: opts.inputField,
|
|
537
|
+
outputField: opts.outputField,
|
|
538
|
+
predictions: (result.predictions ?? []).filter((p) => allowed.has(p.value)),
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// ---------------------------------------------------------------------------
|
|
543
|
+
// 5. Natural-language export
|
|
544
|
+
// ---------------------------------------------------------------------------
|
|
545
|
+
|
|
546
|
+
const EXPORT_FORMATS: ExportFormat[] = ['xlsx', 'xls', 'pdf', 'csv', 'tsv', 'html', 'json', 'xml', 'md']
|
|
547
|
+
|
|
548
|
+
export type AIExportPlan = {
|
|
549
|
+
format: ExportFormat
|
|
550
|
+
filters: AIFilterClause[]
|
|
551
|
+
sort: AISortClause[]
|
|
552
|
+
groupBy: string[]
|
|
553
|
+
/** Plain-English explanation of how the model read the request. */
|
|
554
|
+
rationale: string
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
export type AIExportOptions = {
|
|
558
|
+
/**
|
|
559
|
+
* Also apply the filter / sort / grouping to the grid (mutating the view) so
|
|
560
|
+
* it mirrors the export. Default FALSE - the export is self-contained (it
|
|
561
|
+
* computes its own rows), so the grid is left untouched unless you opt in.
|
|
562
|
+
*/
|
|
563
|
+
apply?: boolean
|
|
564
|
+
/** Actually download the file. Default true; set false to preview the plan. */
|
|
565
|
+
run?: boolean
|
|
566
|
+
/** Base filename (no extension). Default 'export'. */
|
|
567
|
+
filename?: string
|
|
568
|
+
signal?: AbortSignal
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Turn a natural-language request ("export EU orders from Q2 as a grouped PDF")
|
|
573
|
+
* into an export: the model returns a `{ format, filters, sort, groupBy }` plan
|
|
574
|
+
* against the grid's columns; we apply the filter/sort to the grid and hand the
|
|
575
|
+
* result to the registered export engine (@svgrid/enterprise). Returns the plan
|
|
576
|
+
* so the UI can show what it did (or preview it first with `run: false`).
|
|
577
|
+
*/
|
|
578
|
+
export async function aiExport<
|
|
579
|
+
TFeatures extends TableFeatures,
|
|
580
|
+
TData extends RowData,
|
|
581
|
+
>(
|
|
582
|
+
api: SvGridApi<TFeatures, TData>,
|
|
583
|
+
query: string,
|
|
584
|
+
opts: AIExportOptions = {},
|
|
585
|
+
): Promise<AIExportPlan> {
|
|
586
|
+
const schema = buildColumnSchema(api)
|
|
587
|
+
const prompt =
|
|
588
|
+
`You are an export assistant for a data grid. Translate the user's request ` +
|
|
589
|
+
`into a strict-JSON export plan.\n\n` +
|
|
590
|
+
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
591
|
+
`Output JSON schema:\n` +
|
|
592
|
+
`{ "format": "xlsx"|"xls"|"pdf"|"csv"|"tsv"|"html"|"json"|"xml"|"md", ` +
|
|
593
|
+
`"filters": [{"field":"<column>","operator":"contains"|"equals"|"startsWith"|"greaterThan"|"lessThan"|"isBlank","value":"<string>"}], ` +
|
|
594
|
+
`"sort": [{"field":"<column>","desc":true|false}], ` +
|
|
595
|
+
`"groupBy": ["<column>"], ` +
|
|
596
|
+
`"rationale": "<one sentence>" }\n\n` +
|
|
597
|
+
`Rules: use the format the user names (default "xlsx"); only use column ` +
|
|
598
|
+
`names from the list above; "grouped" / "group by X" -> groupBy. ` +
|
|
599
|
+
`Return JSON only, no prose.\n\n` +
|
|
600
|
+
`User request: ${query}`
|
|
601
|
+
|
|
602
|
+
const plan = await callJSON<AIExportPlan>({
|
|
603
|
+
prompt,
|
|
604
|
+
task: 'export',
|
|
605
|
+
signal: opts.signal,
|
|
606
|
+
maxOutputTokens: 500,
|
|
607
|
+
})
|
|
608
|
+
|
|
609
|
+
// Defensive validation - drop invented fields, clamp the format.
|
|
610
|
+
const valid = new Set(schema.map((c) => c.field))
|
|
611
|
+
plan.format = EXPORT_FORMATS.includes(plan.format) ? plan.format : 'xlsx'
|
|
612
|
+
plan.filters = (plan.filters ?? []).filter((f) => valid.has(f.field))
|
|
613
|
+
plan.sort = (plan.sort ?? []).filter((s) => valid.has(s.field))
|
|
614
|
+
plan.groupBy = (plan.groupBy ?? []).filter((g) => valid.has(g))
|
|
615
|
+
plan.rationale = plan.rationale ?? ''
|
|
616
|
+
|
|
617
|
+
// Optionally mirror the plan onto the grid (opt-in). Off by default so the
|
|
618
|
+
// export never disturbs the user's current view.
|
|
619
|
+
if (opts.apply === true) {
|
|
620
|
+
api.clearAllFilters()
|
|
621
|
+
api.clearSort()
|
|
622
|
+
for (const f of plan.filters) {
|
|
623
|
+
api.setFilter(f.field, { operator: f.operator, value: f.value ?? '' })
|
|
624
|
+
}
|
|
625
|
+
const last = plan.sort[plan.sort.length - 1]
|
|
626
|
+
if (last) api.setSort(last.field, last.desc ? 'desc' : 'asc')
|
|
627
|
+
if (plan.groupBy.length > 0) {
|
|
628
|
+
try {
|
|
629
|
+
api.setGroupBy(plan.groupBy)
|
|
630
|
+
} catch {
|
|
631
|
+
// grouping feature not enabled - the export still groups on its own
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// Planning is always free; WRITING the file uses the export engine registered
|
|
637
|
+
// by @svgrid/enterprise (export-provider seam). Without it, we return the plan
|
|
638
|
+
// so the UI can still show what the AI decided - the download just no-ops.
|
|
639
|
+
const runExport = getExportProvider()
|
|
640
|
+
if (opts.run !== false && runExport) {
|
|
641
|
+
// Compute the export rows from the plan directly (filter + sort + make
|
|
642
|
+
// contiguous by group) rather than reading the grid's reactive displayed
|
|
643
|
+
// rows - so the download always has exactly the intended data.
|
|
644
|
+
const exportRows = applyPlanToRows(api.getData(), plan)
|
|
645
|
+
await runExport(api, {
|
|
646
|
+
format: plan.format,
|
|
647
|
+
filename: opts.filename ?? 'export',
|
|
648
|
+
rows: exportRows,
|
|
649
|
+
...(plan.groupBy.length > 0 ? { groupBy: plan.groupBy } : {}),
|
|
650
|
+
})
|
|
651
|
+
}
|
|
652
|
+
return plan
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** Evaluate one AI filter clause against a raw row value. */
|
|
656
|
+
function matchesClause(row: Record<string, unknown>, clause: AIFilterClause): boolean {
|
|
657
|
+
const v = row[clause.field]
|
|
658
|
+
const val = clause.value ?? ''
|
|
659
|
+
switch (clause.operator) {
|
|
660
|
+
case 'contains':
|
|
661
|
+
return String(v ?? '').toLowerCase().includes(val.toLowerCase())
|
|
662
|
+
case 'equals':
|
|
663
|
+
return String(v ?? '').toLowerCase() === val.toLowerCase()
|
|
664
|
+
case 'startsWith':
|
|
665
|
+
return String(v ?? '').toLowerCase().startsWith(val.toLowerCase())
|
|
666
|
+
case 'greaterThan':
|
|
667
|
+
return Number(v) > Number(val)
|
|
668
|
+
case 'lessThan':
|
|
669
|
+
return Number(v) < Number(val)
|
|
670
|
+
case 'isBlank':
|
|
671
|
+
return v == null || v === ''
|
|
672
|
+
default:
|
|
673
|
+
return true
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** Filter + sort + (stable) group the raw rows per an export plan. */
|
|
678
|
+
function applyPlanToRows<TData extends RowData>(
|
|
679
|
+
data: ReadonlyArray<TData>,
|
|
680
|
+
plan: AIExportPlan,
|
|
681
|
+
): TData[] {
|
|
682
|
+
let rows: TData[] = data.slice()
|
|
683
|
+
if (plan.filters.length > 0) {
|
|
684
|
+
rows = rows.filter((r) =>
|
|
685
|
+
plan.filters.every((f) => matchesClause(r as Record<string, unknown>, f)),
|
|
686
|
+
)
|
|
687
|
+
}
|
|
688
|
+
const last = plan.sort[plan.sort.length - 1]
|
|
689
|
+
if (last) {
|
|
690
|
+
rows = [...rows].sort((a, b) => {
|
|
691
|
+
const av = (a as Record<string, unknown>)[last.field]
|
|
692
|
+
const bv = (b as Record<string, unknown>)[last.field]
|
|
693
|
+
const na = Number(av)
|
|
694
|
+
const nb = Number(bv)
|
|
695
|
+
let cmp: number
|
|
696
|
+
if (Number.isFinite(na) && Number.isFinite(nb)) cmp = na - nb
|
|
697
|
+
else cmp = String(av ?? '').localeCompare(String(bv ?? ''))
|
|
698
|
+
return last.desc ? -cmp : cmp
|
|
699
|
+
})
|
|
700
|
+
}
|
|
701
|
+
// Contiguous grouping (first-seen order) so PDF group rows + Excel outline
|
|
702
|
+
// line up.
|
|
703
|
+
if (plan.groupBy.length > 0) {
|
|
704
|
+
const buckets = new Map<string, TData[]>()
|
|
705
|
+
for (const r of rows) {
|
|
706
|
+
const key = plan.groupBy
|
|
707
|
+
.map((k) => String((r as Record<string, unknown>)[k] ?? ''))
|
|
708
|
+
.join('')
|
|
709
|
+
const bucket = buckets.get(key)
|
|
710
|
+
if (bucket) bucket.push(r)
|
|
711
|
+
else buckets.set(key, [r])
|
|
712
|
+
}
|
|
713
|
+
rows = [...buckets.values()].flat()
|
|
714
|
+
}
|
|
715
|
+
return rows
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// ---------------------------------------------------------------------------
|
|
719
|
+
// 6. Find anomalies
|
|
720
|
+
// ---------------------------------------------------------------------------
|
|
721
|
+
|
|
722
|
+
export type AIAnomaly = {
|
|
723
|
+
/** Index into the SCANNED rows (target order), when the model pins one row. */
|
|
724
|
+
rowIndex?: number
|
|
725
|
+
field?: string
|
|
726
|
+
value?: unknown
|
|
727
|
+
reason: string
|
|
728
|
+
severity: 'low' | 'medium' | 'high'
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
export type AIAnomalyResult = {
|
|
732
|
+
anomalies: AIAnomaly[]
|
|
733
|
+
summary: string
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
export type AIAnomalyOptions = {
|
|
737
|
+
/** Which rows to scan. Defaults to the whole dataset. */
|
|
738
|
+
target?: AISummarizeTarget
|
|
739
|
+
/** Optional focus, e.g. "look at pricing and margins". */
|
|
740
|
+
question?: string
|
|
741
|
+
signal?: AbortSignal
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function sliceForTarget<TFeatures extends TableFeatures, TData extends RowData>(
|
|
745
|
+
api: SvGridApi<TFeatures, TData>,
|
|
746
|
+
target: AISummarizeTarget,
|
|
747
|
+
): TData[] {
|
|
748
|
+
const all = api.getData()
|
|
749
|
+
if (target.kind === 'row') {
|
|
750
|
+
const r = all[target.rowIndex]
|
|
751
|
+
return r ? [r] : []
|
|
752
|
+
}
|
|
753
|
+
if (target.kind === 'selection') {
|
|
754
|
+
return target.rowIndices.map((i) => all[i]).filter((r): r is TData => r != null)
|
|
755
|
+
}
|
|
756
|
+
if (target.kind === 'group') {
|
|
757
|
+
return all.filter((r) => (r as Record<string, unknown>)[target.field] === target.value)
|
|
758
|
+
}
|
|
759
|
+
return all.slice()
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Scan a slice of the grid (all / selection / group) for anomalies - outliers,
|
|
764
|
+
* suspicious values, inconsistencies - and return a structured list plus a
|
|
765
|
+
* one-line summary. Pairs naturally with an export: "find the odd ones, then
|
|
766
|
+
* export just those".
|
|
767
|
+
*/
|
|
768
|
+
export async function aiFindAnomalies<
|
|
769
|
+
TFeatures extends TableFeatures,
|
|
770
|
+
TData extends RowData,
|
|
771
|
+
>(
|
|
772
|
+
api: SvGridApi<TFeatures, TData>,
|
|
773
|
+
opts: AIAnomalyOptions = {},
|
|
774
|
+
): Promise<AIAnomalyResult> {
|
|
775
|
+
const rows = sliceForTarget(api, opts.target ?? { kind: 'all' })
|
|
776
|
+
if (rows.length === 0) return { anomalies: [], summary: 'No rows in scope.' }
|
|
777
|
+
|
|
778
|
+
const MAX_SAMPLE = 40
|
|
779
|
+
const sample =
|
|
780
|
+
rows.length <= MAX_SAMPLE
|
|
781
|
+
? rows
|
|
782
|
+
: Array.from(
|
|
783
|
+
{ length: MAX_SAMPLE },
|
|
784
|
+
(_, i) => rows[Math.floor((i / MAX_SAMPLE) * rows.length)]!,
|
|
785
|
+
)
|
|
786
|
+
|
|
787
|
+
const schema = buildColumnSchema(api, 30)
|
|
788
|
+
const prompt =
|
|
789
|
+
`You are a data-quality analyst. Scan the rows below for anomalies: ` +
|
|
790
|
+
`numeric outliers, impossible / inconsistent values, unexpected blanks, ` +
|
|
791
|
+
`and values that break the pattern of the column.\n\n` +
|
|
792
|
+
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
793
|
+
`Rows (index is 0-based into this list):\n` +
|
|
794
|
+
`${sample.map((r, i) => `${i}: ${JSON.stringify(r)}`).join('\n')}\n\n` +
|
|
795
|
+
(opts.question ? `Focus: ${opts.question}\n\n` : '') +
|
|
796
|
+
`Return strict JSON only:\n` +
|
|
797
|
+
`{ "anomalies": [{"rowIndex": <number|null>, "field": "<column|null>", ` +
|
|
798
|
+
`"reason": "<why it's odd>", "severity": "low"|"medium"|"high"}], ` +
|
|
799
|
+
`"summary": "<one sentence>" }`
|
|
800
|
+
|
|
801
|
+
const result = await callJSON<AIAnomalyResult>({
|
|
802
|
+
prompt,
|
|
803
|
+
task: 'anomaly',
|
|
804
|
+
signal: opts.signal,
|
|
805
|
+
maxOutputTokens: 800,
|
|
806
|
+
})
|
|
807
|
+
return {
|
|
808
|
+
anomalies: result.anomalies ?? [],
|
|
809
|
+
summary: result.summary ?? '',
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// ---------------------------------------------------------------------------
|
|
814
|
+
// 7. Natural-language chart ("chart this")
|
|
815
|
+
// ---------------------------------------------------------------------------
|
|
816
|
+
|
|
817
|
+
export type AIChartType = 'bar' | 'line' | 'area' | 'pie'
|
|
818
|
+
|
|
819
|
+
export type AIChartPlan = {
|
|
820
|
+
type: AIChartType
|
|
821
|
+
/** Group-by (category-axis) column field, or null. */
|
|
822
|
+
dimension: string | null
|
|
823
|
+
/** Split-by column field: one series per distinct value, or null. */
|
|
824
|
+
series: string | null
|
|
825
|
+
/** Measure (value-axis) column field, or null. */
|
|
826
|
+
measure: string | null
|
|
827
|
+
reduce: 'sum' | 'avg' | 'count'
|
|
828
|
+
stacked: boolean
|
|
829
|
+
logScale: boolean
|
|
830
|
+
timeAxis: boolean
|
|
831
|
+
valueFormat: 'number' | 'currency' | 'percent'
|
|
832
|
+
rationale: string
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
export type AIChartOptions = {
|
|
836
|
+
/** Apply the plan to the grid's chart panel (open + configure). Default false. */
|
|
837
|
+
apply?: boolean
|
|
838
|
+
signal?: AbortSignal
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* Translate a natural-language request into a chart plan for the grid's built-in
|
|
843
|
+
* `charting` panel. Validates every field against the real schema, then (with
|
|
844
|
+
* `apply: true`) pushes it into the panel through `api.configureChart`.
|
|
845
|
+
*/
|
|
846
|
+
export async function aiChart<
|
|
847
|
+
TFeatures extends TableFeatures,
|
|
848
|
+
TData extends RowData,
|
|
849
|
+
>(
|
|
850
|
+
api: SvGridApi<TFeatures, TData>,
|
|
851
|
+
query: string,
|
|
852
|
+
opts: AIChartOptions = {},
|
|
853
|
+
): Promise<AIChartPlan> {
|
|
854
|
+
const schema = buildColumnSchema(api)
|
|
855
|
+
const prompt =
|
|
856
|
+
`You are a charting assistant for a data grid. Translate the user's request ` +
|
|
857
|
+
`into a strict-JSON chart plan the grid can render.\n\n` +
|
|
858
|
+
`Columns:\n${schemaToPromptBlock(schema)}\n\n` +
|
|
859
|
+
`Output JSON schema:\n` +
|
|
860
|
+
`{ "type": "bar"|"line"|"area"|"pie", ` +
|
|
861
|
+
`"dimension": "<a categorical column to group by>", ` +
|
|
862
|
+
`"series": "<a second categorical column to split into series, or null>", ` +
|
|
863
|
+
`"measure": "<a numeric column to aggregate>", ` +
|
|
864
|
+
`"reduce": "sum"|"avg"|"count", ` +
|
|
865
|
+
`"stacked": true|false, ` +
|
|
866
|
+
`"logScale": true|false, ` +
|
|
867
|
+
`"timeAxis": true|false, ` +
|
|
868
|
+
`"valueFormat": "number"|"currency"|"percent", ` +
|
|
869
|
+
`"rationale": "<one-sentence explanation>" }\n\n` +
|
|
870
|
+
`Rules: pick "dimension" and "series" from text/date columns and "measure" ` +
|
|
871
|
+
`from a numeric column; use only column names from the list above; ` +
|
|
872
|
+
`"stacked"/"stack" -> stacked:true; "log"/"logarithmic" -> logScale:true; ` +
|
|
873
|
+
`"over time"/"by date"/a date dimension -> timeAxis:true; ` +
|
|
874
|
+
`money/revenue/price/$ -> valueFormat:"currency"; rate/%/share -> valueFormat:"percent"; ` +
|
|
875
|
+
`else valueFormat:"number". default reduce is "sum". ` +
|
|
876
|
+
`Return JSON only, no prose.\n\n` +
|
|
877
|
+
`User request: ${query}`
|
|
878
|
+
|
|
879
|
+
const plan = await callJSON<AIChartPlan>({
|
|
880
|
+
prompt,
|
|
881
|
+
task: 'chart',
|
|
882
|
+
signal: opts.signal,
|
|
883
|
+
maxOutputTokens: 300,
|
|
884
|
+
})
|
|
885
|
+
|
|
886
|
+
const valid = new Set(schema.map((c) => c.field))
|
|
887
|
+
const numericFields = new Set(schema.filter((c) => c.type === 'number').map((c) => c.field))
|
|
888
|
+
const CHART_TYPES: AIChartType[] = ['bar', 'line', 'area', 'pie']
|
|
889
|
+
plan.type = CHART_TYPES.includes(plan.type) ? plan.type : 'bar'
|
|
890
|
+
plan.dimension = plan.dimension && valid.has(plan.dimension) ? plan.dimension : null
|
|
891
|
+
plan.series = plan.series && valid.has(plan.series) && plan.series !== plan.dimension ? plan.series : null
|
|
892
|
+
plan.measure =
|
|
893
|
+
plan.measure && numericFields.has(plan.measure)
|
|
894
|
+
? plan.measure
|
|
895
|
+
: (schema.find((c) => c.type === 'number')?.field ?? null)
|
|
896
|
+
plan.reduce = ['sum', 'avg', 'count'].includes(plan.reduce) ? plan.reduce : 'sum'
|
|
897
|
+
plan.stacked = plan.stacked === true
|
|
898
|
+
plan.logScale = plan.logScale === true
|
|
899
|
+
plan.timeAxis = plan.timeAxis === true
|
|
900
|
+
plan.valueFormat = ['number', 'currency', 'percent'].includes(plan.valueFormat) ? plan.valueFormat : 'number'
|
|
901
|
+
plan.rationale = plan.rationale ?? ''
|
|
902
|
+
|
|
903
|
+
if (opts.apply === true) {
|
|
904
|
+
const cfg = api as unknown as { configureChart?: (c: Record<string, unknown>) => void }
|
|
905
|
+
cfg.configureChart?.({
|
|
906
|
+
open: true,
|
|
907
|
+
type: plan.type,
|
|
908
|
+
dimension: plan.dimension,
|
|
909
|
+
series: plan.series,
|
|
910
|
+
measure: plan.measure,
|
|
911
|
+
reduce: plan.reduce,
|
|
912
|
+
stacked: plan.stacked,
|
|
913
|
+
logScale: plan.logScale,
|
|
914
|
+
timeAxis: plan.timeAxis,
|
|
915
|
+
valueFormat: plan.valueFormat,
|
|
916
|
+
})
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
return plan
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* Wire the grid's chart-panel AI button to the model: registers a handler (via
|
|
924
|
+
* `api.setChartAiHandler`) that runs `aiChart` and returns the plan for the
|
|
925
|
+
* panel to apply + explain. Call once after `onApiReady`. `installEnterprise`
|
|
926
|
+
* calls this for you.
|
|
927
|
+
*/
|
|
928
|
+
export function enableAiCharting<
|
|
929
|
+
TFeatures extends TableFeatures,
|
|
930
|
+
TData extends RowData,
|
|
931
|
+
>(api: SvGridApi<TFeatures, TData>): void {
|
|
932
|
+
const hook = api as unknown as {
|
|
933
|
+
setChartAiHandler?: (
|
|
934
|
+
fn: ((prompt: string) => Promise<Record<string, unknown> | null>) | null,
|
|
935
|
+
) => void
|
|
936
|
+
}
|
|
937
|
+
hook.setChartAiHandler?.(async (prompt: string) => {
|
|
938
|
+
const plan = await aiChart(api, prompt)
|
|
939
|
+
return {
|
|
940
|
+
type: plan.type,
|
|
941
|
+
dimension: plan.dimension,
|
|
942
|
+
series: plan.series,
|
|
943
|
+
measure: plan.measure,
|
|
944
|
+
reduce: plan.reduce,
|
|
945
|
+
stacked: plan.stacked,
|
|
946
|
+
logScale: plan.logScale,
|
|
947
|
+
timeAxis: plan.timeAxis,
|
|
948
|
+
valueFormat: plan.valueFormat,
|
|
949
|
+
rationale: plan.rationale,
|
|
950
|
+
}
|
|
951
|
+
})
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
export function disableAiCharting<
|
|
955
|
+
TFeatures extends TableFeatures,
|
|
956
|
+
TData extends RowData,
|
|
957
|
+
>(api: SvGridApi<TFeatures, TData>): void {
|
|
958
|
+
const hook = api as unknown as { setChartAiHandler?: (fn: null) => void }
|
|
959
|
+
hook.setChartAiHandler?.(null)
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// ---------------------------------------------------------------------------
|
|
963
|
+
// 8. Mock provider for examples + tests
|
|
964
|
+
// ---------------------------------------------------------------------------
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* A deterministic provider that returns canned, schema-shaped responses
|
|
968
|
+
* for each task. Wire it in via `setAIProvider(mockAIProvider)` to make
|
|
969
|
+
* the AI demo work end-to-end without a real model key. Not for production.
|
|
970
|
+
*/
|
|
971
|
+
export const mockAIProvider: AIProvider = async (req) => {
|
|
972
|
+
// Tiny artificial delay so the UI's "thinking" state is visible.
|
|
973
|
+
await new Promise((r) => setTimeout(r, 350 + Math.random() * 400))
|
|
974
|
+
|
|
975
|
+
if (req.task === 'filter') {
|
|
976
|
+
const q = extractUserQuery(req.prompt)
|
|
977
|
+
return JSON.stringify(buildMockFilter(req.prompt, q))
|
|
978
|
+
}
|
|
979
|
+
if (req.task === 'smart-fill') {
|
|
980
|
+
return JSON.stringify(buildMockSmartFill(req.prompt))
|
|
981
|
+
}
|
|
982
|
+
if (req.task === 'summarize') {
|
|
983
|
+
return JSON.stringify(buildMockSummary(req.prompt))
|
|
984
|
+
}
|
|
985
|
+
if (req.task === 'classify') {
|
|
986
|
+
return JSON.stringify(buildMockClassify(req.prompt))
|
|
987
|
+
}
|
|
988
|
+
if (req.task === 'export') {
|
|
989
|
+
return JSON.stringify(buildMockExport(req.prompt))
|
|
990
|
+
}
|
|
991
|
+
if (req.task === 'anomaly') {
|
|
992
|
+
return JSON.stringify(buildMockAnomaly(req.prompt))
|
|
993
|
+
}
|
|
994
|
+
if (req.task === 'chart') {
|
|
995
|
+
return JSON.stringify(buildMockChart(req.prompt))
|
|
996
|
+
}
|
|
997
|
+
return '{}'
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function buildMockChart(prompt: string): AIChartPlan {
|
|
1001
|
+
const q = extractUserRequest(prompt)
|
|
1002
|
+
const typed = extractFieldTypes(prompt)
|
|
1003
|
+
const textFields = typed.filter((f) => f.type === 'string' || f.type === 'date').map((f) => f.name)
|
|
1004
|
+
const numberFields = typed.filter((f) => f.type === 'number').map((f) => f.name)
|
|
1005
|
+
|
|
1006
|
+
const type: AIChartType =
|
|
1007
|
+
/\bline\b|\btrend\b|over time/.test(q) ? 'line'
|
|
1008
|
+
: /\barea\b/.test(q) ? 'area'
|
|
1009
|
+
: /\bpie\b|share|proportion|breakdown/.test(q) ? 'pie'
|
|
1010
|
+
: 'bar'
|
|
1011
|
+
|
|
1012
|
+
const byMatch = q.match(/\bby\s+([a-z0-9_ ]+?)(?:\s+(?:split|stacked|grouped|by|as|,|$))/)
|
|
1013
|
+
const pickText = (hint?: string): string | null => {
|
|
1014
|
+
if (hint) {
|
|
1015
|
+
const f = textFields.find((t) => t.toLowerCase() === hint.trim() || (hint.trim().length >= 4 && t.toLowerCase().includes(hint.trim())))
|
|
1016
|
+
if (f) return f
|
|
1017
|
+
}
|
|
1018
|
+
return null
|
|
1019
|
+
}
|
|
1020
|
+
const dimension = pickText(byMatch?.[1]) ?? textFields[0] ?? null
|
|
1021
|
+
const series =
|
|
1022
|
+
/\b(split|stack(?:ed)?|by product|by category|per)\b/.test(q)
|
|
1023
|
+
? (textFields.find((t) => t !== dimension) ?? null)
|
|
1024
|
+
: null
|
|
1025
|
+
const measure = numberFields.find((n) => q.includes(n.toLowerCase())) ?? numberFields[0] ?? null
|
|
1026
|
+
const reduce: 'sum' | 'avg' | 'count' =
|
|
1027
|
+
/\b(average|avg|mean)\b/.test(q) ? 'avg' : /\b(count|number of|how many)\b/.test(q) ? 'count' : 'sum'
|
|
1028
|
+
const stacked = /\bstack(ed)?\b/.test(q)
|
|
1029
|
+
const logScale = /\b(log|logarithmic)\b/.test(q)
|
|
1030
|
+
const timeAxis = /\b(over time|by date|by day|by month|by week|time series|timeline|trend)\b/.test(q)
|
|
1031
|
+
const valueFormat: 'number' | 'currency' | 'percent' =
|
|
1032
|
+
/\b(currency|money|revenue|sales|price|cost|\$|dollar)\b/.test(q) || /(price|revenue|amount|cost|sales)/i.test(measure ?? '')
|
|
1033
|
+
? 'currency'
|
|
1034
|
+
: /\b(percent|percentage|%|rate|share)\b/.test(q)
|
|
1035
|
+
? 'percent'
|
|
1036
|
+
: 'number'
|
|
1037
|
+
|
|
1038
|
+
return {
|
|
1039
|
+
type, dimension, series, measure, reduce, stacked, logScale, timeAxis, valueFormat,
|
|
1040
|
+
rationale:
|
|
1041
|
+
`${type} chart of ${reduce}(${measure ?? 'value'}) by ${dimension ?? 'category'}` +
|
|
1042
|
+
`${series ? `, split by ${series}` : ''}${stacked ? ', stacked' : ''}` +
|
|
1043
|
+
`${logScale ? ', log scale' : ''}${timeAxis ? ', date axis' : ''} (mock - wire a real model for genuine parsing).`,
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
function extractUserRequest(prompt: string): string {
|
|
1048
|
+
const m = prompt.match(/User request:\s*([\s\S]+)$/)
|
|
1049
|
+
return (m?.[1] ?? '').trim().toLowerCase()
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
function buildMockExport(prompt: string): AIExportPlan {
|
|
1053
|
+
const q = extractUserRequest(prompt)
|
|
1054
|
+
const fields = extractFields(prompt)
|
|
1055
|
+
// Reuse the filter mock (it reads "User query:"; feed it a compatible line).
|
|
1056
|
+
const filterPlan = buildMockFilter(prompt + `\nUser query: ${q}\n`, q)
|
|
1057
|
+
|
|
1058
|
+
// Format keyword routing.
|
|
1059
|
+
const format: ExportFormat =
|
|
1060
|
+
/\bpdf\b/.test(q) ? 'pdf'
|
|
1061
|
+
: /\bxls\b(?!x)/.test(q) || /97-2003|legacy excel/.test(q) ? 'xls'
|
|
1062
|
+
: /\b(xlsx|excel|spreadsheet|workbook)\b/.test(q) ? 'xlsx'
|
|
1063
|
+
: /\b(markdown|md)\b/.test(q) ? 'md'
|
|
1064
|
+
: /\bjson\b/.test(q) ? 'json'
|
|
1065
|
+
: /\bxml\b/.test(q) ? 'xml'
|
|
1066
|
+
: /\btsv\b/.test(q) ? 'tsv'
|
|
1067
|
+
: /\bhtml\b/.test(q) ? 'html'
|
|
1068
|
+
: /\bcsv\b/.test(q) ? 'csv'
|
|
1069
|
+
: 'xlsx'
|
|
1070
|
+
|
|
1071
|
+
// Grouping: "group by X" / "grouped by X", else "grouped" -> a categorical field.
|
|
1072
|
+
const groupBy: string[] = []
|
|
1073
|
+
const byMatch = q.match(/group(?:ed)?\s+by\s+([a-z0-9_ ,]+)/)
|
|
1074
|
+
if (byMatch) {
|
|
1075
|
+
for (const token of byMatch[1]!.split(/[, ]+/).filter(Boolean)) {
|
|
1076
|
+
// Exact field match, or a substring match only for tokens long enough to
|
|
1077
|
+
// be meaningful (so "a"/"as" don't match "amount").
|
|
1078
|
+
const f = fields.find(
|
|
1079
|
+
(ff) => ff.toLowerCase() === token || (token.length >= 4 && ff.toLowerCase().includes(token)),
|
|
1080
|
+
)
|
|
1081
|
+
if (f && !groupBy.includes(f)) groupBy.push(f)
|
|
1082
|
+
}
|
|
1083
|
+
} else if (/\bgroup(ed)?\b/.test(q)) {
|
|
1084
|
+
const cat = fields.find((f) => /region|country|category|status|stage|type|group|dept|team/i.test(f))
|
|
1085
|
+
if (cat) groupBy.push(cat)
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
return {
|
|
1089
|
+
format,
|
|
1090
|
+
filters: filterPlan.filters,
|
|
1091
|
+
sort: filterPlan.sort,
|
|
1092
|
+
groupBy,
|
|
1093
|
+
rationale: `Export as ${format}${groupBy.length ? `, grouped by ${groupBy.join(' / ')}` : ''}${filterPlan.filters.length ? `; ${filterPlan.rationale}` : ''}`,
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
function buildMockAnomaly(prompt: string): AIAnomalyResult {
|
|
1098
|
+
// Parse the sampled rows, flag the numeric outliers per numeric field.
|
|
1099
|
+
const rowsBlock = prompt.match(/Rows \(index is 0-based into this list\):\n([\s\S]*?)\n\n/)?.[1] ?? ''
|
|
1100
|
+
const parsed = rowsBlock
|
|
1101
|
+
.split('\n')
|
|
1102
|
+
.map((line) => {
|
|
1103
|
+
const m = line.match(/^(\d+):\s*(\{[\s\S]*\})$/)
|
|
1104
|
+
if (!m) return null
|
|
1105
|
+
const row = safeParse(m[2]!) as Record<string, unknown> | null
|
|
1106
|
+
return row ? { idx: parseInt(m[1]!, 10), row } : null
|
|
1107
|
+
})
|
|
1108
|
+
.filter((r): r is { idx: number; row: Record<string, unknown> } => !!r)
|
|
1109
|
+
|
|
1110
|
+
if (parsed.length === 0) {
|
|
1111
|
+
return { anomalies: [], summary: 'No rows to scan (mock).' }
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// Genuinely numeric fields only: every value is null or a real number (so
|
|
1115
|
+
// booleans like `inStock` and id-ish strings are excluded). Also skip
|
|
1116
|
+
// identifier / row-index columns - a max "id" isn't an anomaly.
|
|
1117
|
+
const isIdLike = (f: string) => /(^id$|_id$|index|idx|^#|guid|uuid|serial|rownum)/i.test(f)
|
|
1118
|
+
const numericFields = Object.keys(parsed[0]!.row).filter(
|
|
1119
|
+
(f) =>
|
|
1120
|
+
!isIdLike(f) &&
|
|
1121
|
+
parsed.some((p) => typeof p.row[f] === 'number') &&
|
|
1122
|
+
parsed.every((p) => p.row[f] == null || typeof p.row[f] === 'number'),
|
|
1123
|
+
)
|
|
1124
|
+
|
|
1125
|
+
const anomalies: AIAnomaly[] = []
|
|
1126
|
+
for (const f of numericFields.slice(0, 2)) {
|
|
1127
|
+
let maxIdx = -1
|
|
1128
|
+
let maxVal = -Infinity
|
|
1129
|
+
for (const p of parsed) {
|
|
1130
|
+
const n = Number(p.row[f])
|
|
1131
|
+
if (Number.isFinite(n) && n > maxVal) {
|
|
1132
|
+
maxVal = n
|
|
1133
|
+
maxIdx = p.idx
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
if (maxIdx >= 0) {
|
|
1137
|
+
anomalies.push({
|
|
1138
|
+
rowIndex: maxIdx,
|
|
1139
|
+
field: f,
|
|
1140
|
+
value: maxVal,
|
|
1141
|
+
reason: `${f} = ${maxVal} is the highest in the sample and may be an outlier`,
|
|
1142
|
+
severity: 'medium',
|
|
1143
|
+
})
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
return {
|
|
1148
|
+
anomalies,
|
|
1149
|
+
summary:
|
|
1150
|
+
anomalies.length > 0
|
|
1151
|
+
? `Flagged ${anomalies.length} potential outlier${anomalies.length === 1 ? '' : 's'} (mock heuristic - wire a real model for genuine analysis).`
|
|
1152
|
+
: 'No obvious anomalies in the sample (mock).',
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
function extractUserQuery(prompt: string): string {
|
|
1157
|
+
const m = prompt.match(/User query:\s*(.+?)\n/)
|
|
1158
|
+
return (m?.[1] ?? '').toLowerCase()
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
function extractFields(prompt: string): string[] {
|
|
1162
|
+
const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
|
|
1163
|
+
if (!m) return []
|
|
1164
|
+
return (m[1] ?? '')
|
|
1165
|
+
.split('\n')
|
|
1166
|
+
.map((l) => l.match(/^- (\w+)/)?.[1])
|
|
1167
|
+
.filter((s): s is string => !!s)
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
/** Parse the "- name (type): ..." schema block into {name, type} pairs. */
|
|
1171
|
+
function extractFieldTypes(prompt: string): Array<{ name: string; type: string }> {
|
|
1172
|
+
const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
|
|
1173
|
+
if (!m) return []
|
|
1174
|
+
return (m[1] ?? '')
|
|
1175
|
+
.split('\n')
|
|
1176
|
+
.map((l) => {
|
|
1177
|
+
const mm = l.match(/^- (\w+)\s*\((\w+)\)/)
|
|
1178
|
+
return mm ? { name: mm[1]!, type: mm[2]! } : null
|
|
1179
|
+
})
|
|
1180
|
+
.filter((x): x is { name: string; type: string } => !!x)
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
function buildMockFilter(prompt: string, q: string): AIFilterResult {
|
|
1184
|
+
const fields = extractFields(prompt)
|
|
1185
|
+
const filters: AIFilterClause[] = []
|
|
1186
|
+
const sort: AISortClause[] = []
|
|
1187
|
+
const rationale: string[] = []
|
|
1188
|
+
|
|
1189
|
+
// Greedy keyword routing. Real model would be smarter; this only needs
|
|
1190
|
+
// to convince the demo viewer the pipeline works.
|
|
1191
|
+
const numberWord = q.match(/(?:over|above|>|greater than)\s+\$?([\d.,]+)([kmb])?/)
|
|
1192
|
+
const lessWord = q.match(/(?:under|below|<|less than)\s+\$?([\d.,]+)([kmb])?/)
|
|
1193
|
+
// Pick a NUMBER-typed field (never a boolean like `inStock`), money-named
|
|
1194
|
+
// ones first so "$300" targets price/amount rather than a count/index.
|
|
1195
|
+
const numberTyped = extractFieldTypes(prompt).filter((f) => f.type === 'number').map((f) => f.name)
|
|
1196
|
+
const moneyRe = /(price|amount|cost|revenue|total|value|salary|arr|fee|spend|budget|sales)/i
|
|
1197
|
+
const numberPool = numberTyped.length > 0 ? numberTyped : fields
|
|
1198
|
+
const numberFields = [
|
|
1199
|
+
...numberPool.filter((f) => moneyRe.test(f)),
|
|
1200
|
+
...numberPool.filter((f) => !moneyRe.test(f)),
|
|
1201
|
+
]
|
|
1202
|
+
|
|
1203
|
+
if (numberWord && numberFields[0]) {
|
|
1204
|
+
const raw = parseFloat(numberWord[1]!.replace(/,/g, ''))
|
|
1205
|
+
const mul = numberWord[2] === 'k' ? 1_000 : numberWord[2] === 'm' ? 1_000_000 : numberWord[2] === 'b' ? 1_000_000_000 : 1
|
|
1206
|
+
filters.push({ field: numberFields[0], operator: 'greaterThan', value: String(raw * mul) })
|
|
1207
|
+
rationale.push(`amount > ${raw}${numberWord[2] ?? ''}`)
|
|
1208
|
+
} else if (lessWord && numberFields[0]) {
|
|
1209
|
+
const raw = parseFloat(lessWord[1]!.replace(/,/g, ''))
|
|
1210
|
+
const mul = lessWord[2] === 'k' ? 1_000 : lessWord[2] === 'm' ? 1_000_000 : 1
|
|
1211
|
+
filters.push({ field: numberFields[0], operator: 'lessThan', value: String(raw * mul) })
|
|
1212
|
+
rationale.push(`amount < ${raw}${lessWord[2] ?? ''}`)
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// Quoted phrases -> contains on a likely text field.
|
|
1216
|
+
const quote = q.match(/"([^"]+)"|'([^']+)'/)
|
|
1217
|
+
const textFields = fields.filter((f) => /(name|company|customer|title|owner|status|region|category|industry)/i.test(f))
|
|
1218
|
+
if (quote) {
|
|
1219
|
+
const term = quote[1] ?? quote[2] ?? ''
|
|
1220
|
+
if (textFields[0]) {
|
|
1221
|
+
filters.push({ field: textFields[0], operator: 'contains', value: term })
|
|
1222
|
+
rationale.push(`text contains "${term}"`)
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
// Person-name routing -> match owner/contact fields.
|
|
1227
|
+
const personOwners = ['sasha', 'jamie', 'casey', 'drew', 'robin', 'morgan', 'riley', 'quinn']
|
|
1228
|
+
for (const n of personOwners) {
|
|
1229
|
+
if (q.includes(n)) {
|
|
1230
|
+
const ownerField = fields.find((f) => /owner|rep|assigned/i.test(f)) ?? fields.find((f) => /name/i.test(f))
|
|
1231
|
+
if (ownerField) {
|
|
1232
|
+
filters.push({ field: ownerField, operator: 'contains', value: n })
|
|
1233
|
+
rationale.push(`owner ~ "${n}"`)
|
|
1234
|
+
break
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// Region routing.
|
|
1240
|
+
for (const r of ['NA', 'EMEA', 'APAC', 'LATAM']) {
|
|
1241
|
+
if (q.toUpperCase().includes(r)) {
|
|
1242
|
+
const regionField = fields.find((f) => /region/i.test(f))
|
|
1243
|
+
if (regionField) {
|
|
1244
|
+
filters.push({ field: regionField, operator: 'equals', value: r })
|
|
1245
|
+
rationale.push(`region = ${r}`)
|
|
1246
|
+
break
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// Status routing - any token in the query that matches a known status.
|
|
1252
|
+
for (const s of ['active', 'pending', 'won', 'lost', 'live', 'paused', 'shipped', 'delivered']) {
|
|
1253
|
+
if (q.includes(s)) {
|
|
1254
|
+
const f = fields.find((f) => /status|stage/i.test(f))
|
|
1255
|
+
if (f) {
|
|
1256
|
+
filters.push({ field: f, operator: 'equals', value: s })
|
|
1257
|
+
rationale.push(`status = ${s}`)
|
|
1258
|
+
break
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// Sort detection.
|
|
1264
|
+
if (/(highest|largest|biggest|top|most)/.test(q)) {
|
|
1265
|
+
const f = numberFields[0]
|
|
1266
|
+
if (f) { sort.push({ field: f, desc: true }); rationale.push(`sort by ${f} desc`) }
|
|
1267
|
+
} else if (/(lowest|smallest|least|cheapest)/.test(q)) {
|
|
1268
|
+
const f = numberFields[0]
|
|
1269
|
+
if (f) { sort.push({ field: f, desc: false }); rationale.push(`sort by ${f} asc`) }
|
|
1270
|
+
} else if (/(newest|recent|latest)/.test(q)) {
|
|
1271
|
+
const dateField = fields.find((f) => /date|at|time/i.test(f))
|
|
1272
|
+
if (dateField) { sort.push({ field: dateField, desc: true }); rationale.push(`sort by ${dateField} desc`) }
|
|
1273
|
+
} else if (/(oldest)/.test(q)) {
|
|
1274
|
+
const dateField = fields.find((f) => /date|at|time/i.test(f))
|
|
1275
|
+
if (dateField) { sort.push({ field: dateField, desc: false }); rationale.push(`sort by ${dateField} asc`) }
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
return {
|
|
1279
|
+
filters,
|
|
1280
|
+
sort,
|
|
1281
|
+
rationale: rationale.length
|
|
1282
|
+
? `Interpreted: ${rationale.join(' AND ')}.`
|
|
1283
|
+
: `Couldn't identify a clear filter for "${q}". Showing all rows.`,
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
function buildMockSmartFill(prompt: string): { predictions: Array<{ rowIndex: number; value: unknown; confidence: number }>; rationale: string } {
|
|
1288
|
+
// Extract the target column and the rows-to-fill block; copy the first
|
|
1289
|
+
// example's "output" pattern verbatim so the demo always returns
|
|
1290
|
+
// something believable. Real models do much better - that's the point.
|
|
1291
|
+
const fieldMatch = prompt.match(/Target column:\s*(\w+)/)
|
|
1292
|
+
const rowsMatch = prompt.match(/Rows to fill:\n([\s\S]*?)\n\n/)
|
|
1293
|
+
const exMatch = prompt.match(/Example 1: input=.* -> output=(.+)/)
|
|
1294
|
+
const targetField = fieldMatch?.[1] ?? ''
|
|
1295
|
+
const rowLines = (rowsMatch?.[1] ?? '').split('\n').filter(Boolean)
|
|
1296
|
+
const exampleOutput = exMatch?.[1] ? safeParse(exMatch[1]) : ''
|
|
1297
|
+
const predictions = rowLines
|
|
1298
|
+
.map((line) => {
|
|
1299
|
+
const m = line.match(/^Row (\d+): (\{.+\})/)
|
|
1300
|
+
if (!m) return null
|
|
1301
|
+
const rowIndex = parseInt(m[1]!, 10)
|
|
1302
|
+
const row = safeParse(m[2]!) as Record<string, unknown> | null
|
|
1303
|
+
if (!row) return null
|
|
1304
|
+
const value = inferFromRow(targetField, row, exampleOutput)
|
|
1305
|
+
return { rowIndex, value, confidence: 0.78 + Math.random() * 0.18 }
|
|
1306
|
+
})
|
|
1307
|
+
.filter((p): p is { rowIndex: number; value: unknown; confidence: number } => !!p)
|
|
1308
|
+
return {
|
|
1309
|
+
predictions,
|
|
1310
|
+
rationale: `Inferred from ${exMatch ? 'the supplied' : 'no'} examples; mocked deterministically for the demo.`,
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
function safeParse(s: string): unknown {
|
|
1315
|
+
try { return JSON.parse(s) } catch { return null }
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
function inferFromRow(field: string, row: Record<string, unknown>, exampleOutput: unknown): unknown {
|
|
1319
|
+
// Mock heuristics that produce a value that "looks right" in common
|
|
1320
|
+
// demo scenarios. The real provider would route through a real model.
|
|
1321
|
+
if (field === 'priority') {
|
|
1322
|
+
const arr = Number(row.arr ?? row.amount ?? row.price ?? 0)
|
|
1323
|
+
return arr > 100_000 ? 'high' : arr > 30_000 ? 'medium' : 'low'
|
|
1324
|
+
}
|
|
1325
|
+
if (field === 'tier') {
|
|
1326
|
+
const arr = Number(row.arr ?? row.amount ?? 0)
|
|
1327
|
+
return arr > 500_000 ? 'enterprise' : arr > 100_000 ? 'growth' : 'starter'
|
|
1328
|
+
}
|
|
1329
|
+
if (field === 'tags' || field === 'category') {
|
|
1330
|
+
return typeof exampleOutput === 'string' ? exampleOutput : 'auto-tag'
|
|
1331
|
+
}
|
|
1332
|
+
if (typeof exampleOutput === 'string') return exampleOutput
|
|
1333
|
+
if (typeof exampleOutput === 'number') return exampleOutput
|
|
1334
|
+
return exampleOutput ?? 'auto'
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
function buildMockSummary(prompt: string): AISummary {
|
|
1338
|
+
const sliceMatch = prompt.match(/Slice size: (\d+) row/)
|
|
1339
|
+
const n = sliceMatch ? parseInt(sliceMatch[1]!, 10) : 0
|
|
1340
|
+
const fields = extractSummaryFields(prompt)
|
|
1341
|
+
return {
|
|
1342
|
+
text:
|
|
1343
|
+
n === 1
|
|
1344
|
+
? `Single record. Notable signals come from ${fields.slice(0, 2).join(' and ') || 'the available fields'}.`
|
|
1345
|
+
: `${n} rows in scope. The distribution skews toward live / active records, with a long tail in ${fields[0] ?? 'amount'}.`,
|
|
1346
|
+
bullets: [
|
|
1347
|
+
`${n} row${n === 1 ? '' : 's'} sampled`,
|
|
1348
|
+
fields[0] ? `Largest variance in ${fields[0]}` : 'Tight clustering across visible fields',
|
|
1349
|
+
fields[1] ? `${fields[1]} concentrates around the median` : 'Few outliers',
|
|
1350
|
+
'Mock summary - wire setAIProvider() to a real model for actual analysis',
|
|
1351
|
+
],
|
|
1352
|
+
highlightedFields: fields.slice(0, 3),
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
function extractSummaryFields(prompt: string): string[] {
|
|
1357
|
+
const m = prompt.match(/Columns:\n([\s\S]*?)\n\n/)
|
|
1358
|
+
if (!m) return []
|
|
1359
|
+
return (m[1] ?? '')
|
|
1360
|
+
.split('\n')
|
|
1361
|
+
.map((l) => l.match(/^- (\w+)/)?.[1])
|
|
1362
|
+
.filter((s): s is string => !!s)
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
function buildMockClassify(prompt: string): { predictions: Array<{ rowIndex: number; value: string; confidence: number }> } {
|
|
1366
|
+
const labelsMatch = prompt.match(/Allowed labels[\s\S]*?:\n([\s\S]*?)\n\n/)
|
|
1367
|
+
// Capture the label up to the first colon, whitespace or end-of-line so
|
|
1368
|
+
// we don't pick up the rubric ("- at-risk: churn signals..." -> "at-risk").
|
|
1369
|
+
const labels = (labelsMatch?.[1] ?? '')
|
|
1370
|
+
.split('\n')
|
|
1371
|
+
.map((l) => l.match(/^-\s*([^\s:]+)/)?.[1])
|
|
1372
|
+
.filter((s): s is string => !!s)
|
|
1373
|
+
const rowLines = (prompt.match(/Rows to classify[\s\S]*?:\n([\s\S]*?)\n\n/)?.[1] ?? '').split('\n').filter(Boolean)
|
|
1374
|
+
const predictions = rowLines.map((line) => {
|
|
1375
|
+
const m = line.match(/^Row (\d+): "(.*)"/)
|
|
1376
|
+
if (!m || labels.length === 0) return null
|
|
1377
|
+
const rowIndex = parseInt(m[1]!, 10)
|
|
1378
|
+
const text = (m[2] ?? '').toLowerCase()
|
|
1379
|
+
// Pick the label whose token appears in the text; otherwise hash.
|
|
1380
|
+
const hit = labels.find((l) => text.includes(l.toLowerCase()))
|
|
1381
|
+
const value = hit ?? labels[Math.abs(hashStr(text)) % labels.length]!
|
|
1382
|
+
return { rowIndex, value, confidence: hit ? 0.92 : 0.6 + Math.random() * 0.2 }
|
|
1383
|
+
}).filter((p): p is { rowIndex: number; value: string; confidence: number } => !!p)
|
|
1384
|
+
return { predictions }
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
function hashStr(s: string): number {
|
|
1388
|
+
let h = 0
|
|
1389
|
+
for (let i = 0; i < s.length; i += 1) h = (h * 31 + s.charCodeAt(i)) | 0
|
|
1390
|
+
return h
|
|
1391
|
+
}
|