@karni/ai-ui 0.0.0-stage → 0.5.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/LICENSE +201 -0
- package/README.md +80 -2
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +395 -0
- package/dist/index.js.map +1 -0
- package/dist/src/ExtractButton.d.ts +27 -0
- package/dist/src/ExtractPreview.d.ts +38 -0
- package/dist/src/hooks.d.ts +8 -0
- package/dist/src/index.d.ts +8 -0
- package/dist/src/roles.d.ts +9 -0
- package/dist/src/types.d.ts +55 -0
- package/package.json +91 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @karni/ai-ui
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React components for the Karni AI extraction module: ExtractButton and the useExtract hook.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@karni/ai-ui) [](https://github.com/cbsshekhawat18-lab/karni/blob/main/LICENSE) [](https://cbsshekhawat18-lab.github.io/karni/ai-extraction/)
|
|
6
|
+
|
|
7
|
+
Experimental. It composes [`@karni/ui`](https://www.npmjs.com/package/@karni/ui) for the [karni-ai](https://pypi.org/project/karni-ai/) module (`karni add ai`):
|
|
8
|
+
|
|
9
|
+
- **`ExtractButton`**: a button that opens a dialog, reads rows of a resource
|
|
10
|
+
from a text, a web page or a PDF (`POST /api/ai/extract/`), shows the import
|
|
11
|
+
preview (proposed rows, a problem per field, the counts), and commits through
|
|
12
|
+
the import's own confirmation. Nothing is saved before the commit.
|
|
13
|
+
- **`useExtract(resource)`**: the mutation behind it, for a flow of your own.
|
|
14
|
+
- **`ExtractPreview`**: the preview and its commit, for a flow of your own.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @karni/ai-ui @karni/ui @tanstack/react-query@5
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Peer dependencies: `react` / `react-dom` (`^18 || ^19`), `@karni/ui` at this package's version (every Karni package is released at one version),
|
|
23
|
+
`@tanstack/react-query` (`^5`). Wrap your app in `<KarniProvider>` as the
|
|
24
|
+
`@karni/ui` README describes. The client's `baseUrl` carries `/api`.
|
|
25
|
+
|
|
26
|
+
## ExtractButton
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
import { ExtractButton } from "@karni/ai-ui";
|
|
30
|
+
|
|
31
|
+
<ExtractButton
|
|
32
|
+
resource="products"
|
|
33
|
+
resourceLabel="products"
|
|
34
|
+
sources={["text", "pdf"]}
|
|
35
|
+
onDone={(job) => toast({ title: `${job.result?.created ?? 0} products added` })}
|
|
36
|
+
/>;
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Prop | Meaning |
|
|
40
|
+
| --------------------- | ----------------------------------------------------------------- |
|
|
41
|
+
| `resource` | the router prefix (`products`) |
|
|
42
|
+
| `resourceLabel` | the resource in words, plural. Default: `resource` |
|
|
43
|
+
| `sources` | the forms offered: `text`, `url`, `pdf` (default: all three) |
|
|
44
|
+
| `onExtracted(result)` | the preview arrived |
|
|
45
|
+
| `onDone(job)` | the commit saved the rows |
|
|
46
|
+
| `slots` | replace `Error`, `Rows`, `Problems`, `Summary` or `ConfirmCommit` |
|
|
47
|
+
|
|
48
|
+
Every other `@karni/ui` Button prop goes to the trigger. A refusal (an AI code:
|
|
49
|
+
a source that cannot be read, a refused address, a spent budget) shows the
|
|
50
|
+
backend's own words.
|
|
51
|
+
|
|
52
|
+
## useExtract
|
|
53
|
+
|
|
54
|
+
```tsx
|
|
55
|
+
import { useImportActions } from "@karni/ui";
|
|
56
|
+
import { useExtract } from "@karni/ai-ui";
|
|
57
|
+
|
|
58
|
+
const extract = useExtract("products");
|
|
59
|
+
const { commit } = useImportActions("products");
|
|
60
|
+
|
|
61
|
+
const preview = await extract.mutateAsync({ text }); // or { url } or { file }
|
|
62
|
+
// preview.rows, preview.problems, preview.result: nothing is saved yet
|
|
63
|
+
commit.mutate(preview.id); // the import's own commit
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`extractRefusal(error)` returns `{code, detail}` for a refused extraction.
|
|
67
|
+
|
|
68
|
+
## Tests
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
npm test
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Links
|
|
75
|
+
|
|
76
|
+
- AI extraction: <https://cbsshekhawat18-lab.github.io/karni/ai-extraction/>
|
|
77
|
+
- The Python module: <https://pypi.org/project/karni-ai/>
|
|
78
|
+
- Karni, the framework this package is part of: <https://github.com/cbsshekhawat18-lab/karni>
|
|
79
|
+
- Changelog: <https://github.com/cbsshekhawat18-lab/karni/blob/main/CHANGELOG.md>
|
|
80
|
+
- Issues: <https://github.com/cbsshekhawat18-lab/karni/issues>
|
|
81
|
+
- License: Apache-2.0. @karni/ai-ui is released with every other Karni package, at one version.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("@karni/ui");c=s(c,1);let l=require("react");l=s(l,1);let u=require("react/jsx-runtime"),d=require("@tanstack/react-query");var f=[{role:`extract-button`,component:`ExtractButton`,package:`@karni/ai-ui`,description:`Reads rows of a resource from a text, a web page or a PDF into the import preview, then commits them.`}];function p(e=c){if(typeof e!=`object`||!e)return!1;let t=e.registerComponentRole;if(typeof t!=`function`)return!1;for(let e of f)t(e.role,e);return!0}function m(e,t,n){return`${e.toLocaleString()} ${e===1?t:n}`}function h(e){return e==null||e===``?(0,u.jsx)(c.EmptyValue,{}):Array.isArray(e)?e.map(String).join(`, `):typeof e==`boolean`?e?`Yes`:`No`:typeof e==`object`?JSON.stringify(e):String(e)}function g(e){let t=[];for(let n of e)for(let e of Object.keys(n))t.includes(e)||t.push(e);return t}function _({rows:e,fields:t}){return(0,u.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-border`,children:(0,u.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,u.jsx)(`caption`,{className:`px-3 py-2 text-left text-sm font-medium text-foreground`,children:`Proposed rows`}),(0,u.jsx)(`thead`,{className:`bg-muted text-left text-xs uppercase text-muted-foreground`,children:(0,u.jsxs)(`tr`,{children:[(0,u.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-medium`,children:`Row`}),t.map(e=>(0,u.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-medium`,children:e},e))]})}),(0,u.jsx)(`tbody`,{children:e.map((e,n)=>(0,u.jsxs)(`tr`,{className:`border-t border-border`,children:[(0,u.jsx)(`th`,{scope:`row`,className:`px-3 py-2 text-left font-normal tabular-nums`,children:n+1}),t.map(t=>(0,u.jsx)(`td`,{className:`px-3 py-2`,children:h(e[t])},t))]},n))})]})})}var v={schema:`Reading`,preview:`Preview`};function y({problems:e}){return(0,u.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-border`,children:(0,u.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,u.jsx)(`caption`,{className:`px-3 py-2 text-left text-sm font-medium text-foreground`,children:`Problems`}),(0,u.jsx)(`thead`,{className:`bg-muted text-left text-xs uppercase text-muted-foreground`,children:(0,u.jsxs)(`tr`,{children:[(0,u.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-medium`,children:`Row`}),(0,u.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-medium`,children:`Field`}),(0,u.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-medium`,children:`Problem`}),(0,u.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-medium`,children:`Found by`})]})}),(0,u.jsx)(`tbody`,{children:e.map((e,t)=>(0,u.jsxs)(`tr`,{className:`border-t border-border`,children:[(0,u.jsx)(`th`,{scope:`row`,className:`px-3 py-2 text-left font-normal tabular-nums`,children:e.row>0?e.row:(0,u.jsx)(c.EmptyValue,{label:`every row`})}),(0,u.jsx)(`td`,{className:`px-3 py-2 font-mono text-xs`,children:e.field||(0,u.jsx)(c.EmptyValue,{label:`the whole row`})}),(0,u.jsx)(`td`,{className:`px-3 py-2`,children:e.message}),(0,u.jsx)(`td`,{className:`px-3 py-2 text-muted-foreground`,children:v[e.source]})]},`${e.row}-${e.field}-${t}`))})]})})}var b={Rows:_,Problems:y,Summary:c.defaultResourceImportSlots.Summary,ConfirmCommit:c.defaultResourceImportSlots.ConfirmCommit,Progress:c.defaultResourceImportSlots.Progress};function x({result:e,resourceLabel:t,onDone:n,onStartOver:r,slots:i}){let a={...b,...i},o=t??e.resource,s=(0,c.useImportJob)(e.resource,e.id).data??e.job,{commit:d}=(0,c.useImportActions)(e.resource),[f,p]=l.useState(!1),h=s.status===`done`,_=s.result??e.result,v=l.useMemo(()=>g(e.rows),[e.rows]);return l.useEffect(()=>{h&&n?.(s)},[h,s.id]),(0,u.jsxs)(`section`,{className:`space-y-3`,"aria-label":`Extraction preview`,"data-step":s.status,children:[(0,u.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:h?`Saved to ${o}: ${m((_?.created??0)+(_?.updated??0),`row`,`rows`)}.`:`Read ${m(e.rows.length,`row`,`rows`)} from ${e.source.label}. Nothing is saved yet.`}),e.rows.length>0?(0,u.jsx)(a.Rows,{rows:e.rows,fields:v}):null,(0,c.isImportInFlight)(s)?(0,u.jsx)(a.Progress,{job:s}):null,_===null?null:(0,u.jsx)(a.Summary,{job:s,result:_}),e.problems.length>0&&!h?(0,u.jsx)(a.Problems,{problems:e.problems}):null,(0,u.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[h?null:(0,u.jsx)(c.Button,{onClick:()=>{d.reset(),p(!0)},disabled:d.isPending||_===null||s.status!==`previewed`,children:`Commit`}),r===void 0?null:(0,u.jsx)(c.Button,{variant:`outline`,onClick:r,disabled:d.isPending,children:`Read another source`})]}),!h&&_!==null?(0,u.jsx)(a.ConfirmCommit,{open:f,onOpenChange:e=>{d.isPending||p(e)},job:s,result:_,resourceLabel:o,pending:d.isPending,error:d.error,onConfirm:()=>d.mutate(s.id,{onSuccess:()=>p(!1)})}):null]})}var S=`/ai/extract/`;function C(e){if(!(e instanceof c.KarniApiError)||typeof e.data!=`object`||e.data===null)return;let t=e.data,n=t.code,r=t.detail;if(typeof n==`string`&&/^AI\d{3}$/.test(n)&&typeof r==`string`)return{code:n,detail:r}}function w(e){let t=(0,c.useKarniClient)(),n=(0,d.useQueryClient)();return(0,d.useMutation)({mutationFn:n=>{if(`file`in n){let r=new FormData;return r.append(`resource`,e),r.append(`file`,n.file),t.request(S,{method:`POST`,body:r})}return t.request(S,{method:`POST`,body:{resource:e,...n}})},onSuccess:t=>{n.setQueryData((0,c.importJobKey)(e,t.id),t.job),n.invalidateQueries({queryKey:c.karniKeys.resource(`ai`)})}})}var T={text:`Text`,url:`Web page`,pdf:`PDF`},E={text:`a text`,url:`a web page`,pdf:`a PDF`};function D(e){let t=e.map(e=>E[e]);return t.length<=1?t[0]??`a source`:`${t.slice(0,-1).join(`, `)} or ${t[t.length-1]}`}var O={AI008:`This resource can't be extracted into`,AI009:`You can't add these rows`,AI010:`This source can't be read`,AI011:`This address can't be fetched`,AI012:`This page can't be read`,AI013:`Your monthly budget is spent`,AI014:`The monthly budget is spent`};function k({error:e,resourceLabel:t}){let n=C(e);return n===void 0?(0,u.jsx)(c.ErrorState,{variant:`inline`,error:e,context:{action:`extract`,resource:t}}):(0,u.jsxs)(`div`,{role:`alert`,className:`rounded-md border border-destructive-border bg-destructive-subtle p-3 text-sm`,children:[(0,u.jsx)(`p`,{className:`font-medium text-foreground`,children:O[n.code]??`The extraction failed`}),(0,u.jsx)(`p`,{className:`text-muted-foreground`,children:n.detail})]})}function A({sources:e,pending:t,onSubmit:n}){let r={text:l.useId(),url:l.useId(),pdf:l.useId()},[i,a]=l.useState(e[0]??`text`),[o,s]=l.useState(``),[d,f]=l.useState(``),[p,m]=l.useState(null),h=e=>{e.preventDefault(),i===`text`?n({text:o}):i===`url`?n({url:d}):p!==null&&n({file:p})},g=e=>e===`text`?(0,u.jsxs)(`div`,{className:`grid gap-1.5`,children:[(0,u.jsx)(c.Label,{htmlFor:r.text,children:`Text to read`}),(0,u.jsx)(c.Textarea,{id:r.text,rows:8,required:!0,value:o,onChange:e=>s(e.target.value)})]}):e===`url`?(0,u.jsxs)(`div`,{className:`grid gap-1.5`,children:[(0,u.jsx)(c.Label,{htmlFor:r.url,children:`Address of the page`}),(0,u.jsx)(c.Input,{id:r.url,type:`url`,required:!0,placeholder:`https://`,value:d,onChange:e=>f(e.target.value)})]}):(0,u.jsxs)(`div`,{className:`grid gap-1.5`,children:[(0,u.jsx)(c.Label,{htmlFor:r.pdf,children:`PDF file`}),(0,u.jsx)(c.Input,{id:r.pdf,type:`file`,accept:`application/pdf,.pdf`,className:`cursor-pointer`,onChange:e=>m(e.target.files?.[0]??null)})]});return(0,u.jsxs)(`form`,{onSubmit:h,className:`space-y-3`,"aria-label":`Source to read`,children:[e.length>1?(0,u.jsxs)(c.Tabs,{value:i,onValueChange:e=>a(e),children:[(0,u.jsx)(c.TabsList,{children:e.map(e=>(0,u.jsx)(c.TabsTrigger,{value:e,children:T[e]},e))}),e.map(e=>(0,u.jsx)(c.TabsContent,{value:e,children:g(e)},e))]}):g(i),(0,u.jsx)(c.PendingButton,{type:`submit`,pending:t,pendingLabel:`Reading…`,disabled:i===`pdf`&&p===null,children:`Extract`})]})}function j(e){let{resource:t,resourceLabel:n,sources:r=[`text`,`url`,`pdf`],onExtracted:i,onDone:a,slots:o,children:s,...d}=e,f=n??t,p=o?.Error??k,[m,h]=l.useState(!1),[g,_]=l.useState(void 0),v=w(t),y=()=>{_(void 0),v.reset()};return(0,u.jsx)(c.Modal,{open:m,onOpenChange:e=>{h(e),e||y()},title:`Extract ${f}`,description:`Read ${f} from ${D(r)}. Nothing is saved until you commit the preview.`,className:`max-w-3xl`,trigger:(0,u.jsx)(c.Button,{"data-karni-role":`extract-button`,...d,children:s??`Extract with AI`}),children:g===void 0?(0,u.jsxs)(`div`,{className:`space-y-3`,children:[(0,u.jsx)(A,{sources:r,pending:v.isPending,onSubmit:e=>v.mutate(e,{onSuccess:e=>{_(e),i?.(e)}})}),v.error!==null&&v.error!==void 0?(0,u.jsx)(p,{error:v.error,resourceLabel:f}):null]}):(0,u.jsx)(x,{result:g,resourceLabel:f,onDone:a,onStartOver:y,slots:o})})}p(),exports.AI_COMPONENT_ROLES=f,exports.EXTRACT_PATH=S,exports.ExtractButton=j,exports.ExtractPreview=x,exports.defaultExtractPreviewSlots=b,exports.extractRefusal=C,exports.registerAiRoles=p,exports.rowFields=g,exports.useExtract=w;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["karniUi","EmptyValue","defaultResourceImportSlots","useImportJob","useImportActions","React","isImportInFlight","Button","KarniApiError","useKarniClient","useQueryClient","useMutation","importJobKey","karniKeys","ErrorState","React","Label","Textarea","Input","Tabs","TabsList","TabsTrigger","TabsContent","PendingButton","Modal","Button","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__copyProps","from","keys","i","n","key","to","except","k","desc","__toESM","mod","isNodeMode","target","_karni_ui","react","react_jsx_runtime","_tanstack_react_query","AI_COMPONENT_ROLES","registerAiRoles","registry","candidate","\"registerComponentRole\"","definition","plural","count","one","many","cell","value","rowFields","seen","row","rows","DefaultRows","fields","field","index","FOUND_BY","DefaultProblems","problems","problem","defaultExtractPreviewSlots","ExtractPreview","Slots","slots","label","resourceLabel","result","job","confirmOpen","setConfirmOpen","done","counts","onDone","commit","onStartOver","open","EXTRACT_PATH","extractRefusal","error","data","code","\"code\"","detail","\"detail\"","useExtract","client","queryClient","input","form","resource","SOURCE_LABELS","SOURCE_WORDS","sourceWords","words","sources","source","REFUSAL_TITLES","DefaultExtractError","refusal","SourceForm","ids","kind","setKind","text","setText","url","setUrl","file","setFile","submit","event","onSubmit","ExtractButton","buttonProps","props","ErrorSlot","setOpen","setResult","extract","startOver","next","children","answer","onExtracted"],"sources":["../src/roles.ts","../src/ExtractPreview.tsx","../src/hooks.ts","../src/ExtractButton.tsx","../src/index.ts"],"sourcesContent":["/** Component-role registration, feature-detected on @karni/ui's registry. */\nimport * as karniUi from \"@karni/ui\";\n\nexport interface ComponentRoleDefinition {\n role: string;\n component: string;\n package: string;\n description: string;\n}\n\nexport const AI_COMPONENT_ROLES: readonly ComponentRoleDefinition[] = [\n {\n role: \"extract-button\",\n component: \"ExtractButton\",\n package: \"@karni/ai-ui\",\n description:\n \"Reads rows of a resource from a text, a web page or a PDF into the import preview, then commits them.\",\n },\n];\n\ntype RegisterComponentRole = (role: string, definition: ComponentRoleDefinition) => void;\n\n/** Experimental. Registers the package's components in @karni/ui's role registry, if any. */\nexport function registerAiRoles(registry: unknown = karniUi): boolean {\n if (typeof registry !== \"object\" || registry === null) return false;\n const candidate = (registry as Record<string, unknown>)[\"registerComponentRole\"];\n if (typeof candidate !== \"function\") return false;\n for (const definition of AI_COMPONENT_ROLES) {\n (candidate as RegisterComponentRole)(definition.role, definition);\n }\n return true;\n}\n","/**\n * <ExtractPreview>: the import preview of an extraction, and its commit. Experimental.\n *\n * Shows the proposed rows, a problem per field (found while reading the\n * answer, or by the import's dry run), the preview's counts, and Commit,\n * which confirms through `@karni/ui`'s `useImportActions(resource).commit`:\n * the import's own commit path. Nothing is saved before that.\n *\n * The counts and the confirmation reuse `@karni/ui`'s import slots\n * (`defaultResourceImportSlots.Summary` and `.ConfirmCommit`), so an\n * extraction reads like a file import. Escape hatch: replace any part with\n * `slots` (Rows, Problems, Summary, ConfirmCommit, Progress).\n */\nimport {\n Button,\n EmptyValue,\n defaultResourceImportSlots,\n isImportInFlight,\n useImportActions,\n useImportJob,\n type ImportConfirmProps,\n type ImportJob,\n type ImportProgressProps,\n type ImportSummaryProps,\n} from \"@karni/ui\";\nimport * as React from \"react\";\nimport type { ExtractProblem, ExtractResult } from \"./types\";\n\n/** Experimental. What the `Rows` slot receives: the proposed rows and their fields. */\nexport interface ExtractRowsProps {\n rows: ReadonlyArray<Record<string, unknown>>;\n fields: readonly string[];\n}\n\n/** Experimental. What the `Problems` slot receives: one problem per field, rows from 1. */\nexport interface ExtractProblemsProps {\n problems: readonly ExtractProblem[];\n}\n\n/** Experimental. The replaceable parts of ExtractPreview. */\nexport interface ExtractPreviewSlots {\n Rows: React.ComponentType<ExtractRowsProps>;\n Problems: React.ComponentType<ExtractProblemsProps>;\n Summary: React.ComponentType<ImportSummaryProps>;\n ConfirmCommit: React.ComponentType<ImportConfirmProps>;\n /** A preview or commit running in Celery (more rows than KARNI_IMPORT_INLINE_ROWS). */\n Progress: React.ComponentType<ImportProgressProps>;\n}\n\nexport interface ExtractPreviewProps {\n /** The answer of `useExtract`. */\n result: ExtractResult;\n /** The resource in words, plural (\"products\"). Default: the router prefix. */\n resourceLabel?: string;\n /** Called once the commit saved the rows (the job is `done`). */\n onDone?: (job: ImportJob) => void;\n /** Shown as \"Read another source\" when given. */\n onStartOver?: () => void;\n slots?: Partial<ExtractPreviewSlots>;\n}\n\nfunction plural(count: number, one: string, many: string): string {\n return `${count.toLocaleString()} ${count === 1 ? one : many}`;\n}\n\nfunction cell(value: unknown): React.ReactNode {\n if (value === undefined || value === null || value === \"\") return <EmptyValue />;\n if (Array.isArray(value)) return value.map(String).join(\", \");\n if (typeof value === \"boolean\") return value ? \"Yes\" : \"No\";\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value);\n}\n\n/** Experimental. The fields the rows use, in the order they first appear. */\nexport function rowFields(rows: ReadonlyArray<Record<string, unknown>>): string[] {\n const seen: string[] = [];\n for (const row of rows) {\n for (const key of Object.keys(row)) if (!seen.includes(key)) seen.push(key);\n }\n return seen;\n}\n\nfunction DefaultRows({ rows, fields }: ExtractRowsProps): React.ReactElement {\n return (\n <div className=\"overflow-x-auto rounded-md border border-border\">\n <table className=\"w-full text-sm\">\n <caption className=\"px-3 py-2 text-left text-sm font-medium text-foreground\">\n Proposed rows\n </caption>\n <thead className=\"bg-muted text-left text-xs uppercase text-muted-foreground\">\n <tr>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Row\n </th>\n {fields.map((field) => (\n <th key={field} scope=\"col\" className=\"px-3 py-2 font-medium\">\n {field}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {rows.map((row, index) => (\n <tr key={index} className=\"border-t border-border\">\n <th scope=\"row\" className=\"px-3 py-2 text-left font-normal tabular-nums\">\n {index + 1}\n </th>\n {fields.map((field) => (\n <td key={field} className=\"px-3 py-2\">\n {cell(row[field])}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\nconst FOUND_BY: Record<ExtractProblem[\"source\"], string> = {\n schema: \"Reading\",\n preview: \"Preview\",\n};\n\nfunction DefaultProblems({ problems }: ExtractProblemsProps): React.ReactElement {\n return (\n <div className=\"overflow-x-auto rounded-md border border-border\">\n <table className=\"w-full text-sm\">\n <caption className=\"px-3 py-2 text-left text-sm font-medium text-foreground\">\n Problems\n </caption>\n <thead className=\"bg-muted text-left text-xs uppercase text-muted-foreground\">\n <tr>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Row\n </th>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Field\n </th>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Problem\n </th>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Found by\n </th>\n </tr>\n </thead>\n <tbody>\n {problems.map((problem, index) => (\n <tr key={`${problem.row}-${problem.field}-${index}`} className=\"border-t border-border\">\n <th scope=\"row\" className=\"px-3 py-2 text-left font-normal tabular-nums\">\n {problem.row > 0 ? problem.row : <EmptyValue label=\"every row\" />}\n </th>\n <td className=\"px-3 py-2 font-mono text-xs\">\n {problem.field || <EmptyValue label=\"the whole row\" />}\n </td>\n <td className=\"px-3 py-2\">{problem.message}</td>\n <td className=\"px-3 py-2 text-muted-foreground\">{FOUND_BY[problem.source]}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\n/** Experimental. Karni's own slots, exported so a project can wrap one instead of rewriting it. */\nexport const defaultExtractPreviewSlots: ExtractPreviewSlots = {\n Rows: DefaultRows,\n Problems: DefaultProblems,\n Summary: defaultResourceImportSlots.Summary,\n ConfirmCommit: defaultResourceImportSlots.ConfirmCommit,\n Progress: defaultResourceImportSlots.Progress,\n};\n\n/** Experimental. The preview of an extraction, with the import's own commit. */\nexport function ExtractPreview({\n result,\n resourceLabel,\n onDone,\n onStartOver,\n slots,\n}: ExtractPreviewProps): React.ReactElement {\n const Slots: ExtractPreviewSlots = { ...defaultExtractPreviewSlots, ...slots };\n const label = resourceLabel ?? result.resource;\n const jobQuery = useImportJob(result.resource, result.id);\n const job = jobQuery.data ?? result.job;\n const { commit } = useImportActions(result.resource);\n const [confirmOpen, setConfirmOpen] = React.useState(false);\n const done = job.status === \"done\";\n const counts = job.result ?? result.result;\n const fields = React.useMemo(() => rowFields(result.rows), [result.rows]);\n\n React.useEffect(() => {\n if (done) onDone?.(job);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- fire once per completion\n }, [done, job.id]);\n\n return (\n <section className=\"space-y-3\" aria-label=\"Extraction preview\" data-step={job.status}>\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n {done\n ? `Saved to ${label}: ${plural(\n (counts?.created ?? 0) + (counts?.updated ?? 0),\n \"row\",\n \"rows\",\n )}.`\n : `Read ${plural(result.rows.length, \"row\", \"rows\")} from ${result.source.label}. Nothing is saved yet.`}\n </p>\n {result.rows.length > 0 ? <Slots.Rows rows={result.rows} fields={fields} /> : null}\n {isImportInFlight(job) ? <Slots.Progress job={job} /> : null}\n {counts !== null ? <Slots.Summary job={job} result={counts} /> : null}\n {result.problems.length > 0 && !done ? <Slots.Problems problems={result.problems} /> : null}\n <div className=\"flex flex-wrap gap-2\">\n {done ? null : (\n <Button\n onClick={() => {\n commit.reset();\n setConfirmOpen(true);\n }}\n disabled={commit.isPending || counts === null || job.status !== \"previewed\"}\n >\n Commit\n </Button>\n )}\n {onStartOver !== undefined ? (\n <Button variant=\"outline\" onClick={onStartOver} disabled={commit.isPending}>\n Read another source\n </Button>\n ) : null}\n </div>\n {!done && counts !== null ? (\n <Slots.ConfirmCommit\n open={confirmOpen}\n onOpenChange={(open) => {\n if (!commit.isPending) setConfirmOpen(open);\n }}\n job={job}\n result={counts}\n resourceLabel={label}\n pending={commit.isPending}\n error={commit.error}\n onConfirm={() => commit.mutate(job.id, { onSuccess: () => setConfirmOpen(false) })}\n />\n ) : null}\n </section>\n );\n}\n","/**\n * `useExtract(resource)`: a mutation that posts one source to `POST /api/ai/extract/`\n * and resolves with the import preview of the rows read from it. Experimental.\n *\n * Nothing is saved: confirm the preview with `@karni/ui`'s\n * `useImportActions(resource).commit` (the import's own commit). The answer's\n * import job is put in `@karni/ui`'s import job cache, so `useImportJob(resource, id)`\n * has it without a request.\n */\nimport { importJobKey, KarniApiError, karniKeys, useKarniClient } from \"@karni/ui\";\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport type { ExtractInput, ExtractRefusal, ExtractResult } from \"./types\";\n\n/** Experimental. The extraction endpoint, relative to the client's base URL (it carries `/api`). */\nexport const EXTRACT_PATH = \"/ai/extract/\";\n\n/** Experimental. The refusal an extraction answered with (`{code, detail}`), else undefined. */\nexport function extractRefusal(error: unknown): ExtractRefusal | undefined {\n if (!(error instanceof KarniApiError) || typeof error.data !== \"object\" || error.data === null) {\n return undefined;\n }\n const data = error.data as Record<string, unknown>;\n const code = data[\"code\"];\n const detail = data[\"detail\"];\n if (typeof code === \"string\" && /^AI\\d{3}$/.test(code) && typeof detail === \"string\") {\n return { code, detail };\n }\n return undefined;\n}\n\n/** Experimental. Posts one source for `resource` (a router prefix) and resolves with the preview. */\nexport function useExtract(\n resource: string,\n): UseMutationResult<ExtractResult, unknown, ExtractInput> {\n const client = useKarniClient();\n const queryClient = useQueryClient();\n return useMutation<ExtractResult, unknown, ExtractInput>({\n mutationFn: (input) => {\n if (\"file\" in input) {\n const form = new FormData();\n form.append(\"resource\", resource);\n form.append(\"file\", input.file);\n return client.request<ExtractResult>(EXTRACT_PATH, { method: \"POST\", body: form });\n }\n return client.request<ExtractResult>(EXTRACT_PATH, {\n method: \"POST\",\n body: { resource, ...input },\n });\n },\n onSuccess: (result) => {\n queryClient.setQueryData(importJobKey(resource, result.id), result.job);\n // The caller's usage list (GET /api/ai/) has one more call.\n void queryClient.invalidateQueries({ queryKey: karniKeys.resource(\"ai\") });\n },\n });\n}\n","/**\n * <ExtractButton>: read rows of a resource from a text, a web page or a PDF. Experimental.\n *\n * The button opens a dialog with one form per source. Extract posts it to\n * `POST /api/ai/extract/` (`useExtract`) and the dialog then shows the\n * import preview of the rows (`<ExtractPreview>`). Commit saves them through\n * the import's own commit, after the same confirmation a file import asks\n * for. Nothing is saved before.\n *\n * The backend decides everything that matters: who may extract into the\n * resource, which fields the model fills, what each row's problems are. A\n * refusal (an AI code: the source, the URL, the budget) is shown in the\n * backend's words.\n *\n * Escape hatches: every `@karni/ui` Button prop passes through to the\n * trigger. `sources` limits the forms. `slots` replaces the error display\n * and the preview's parts. `useExtract` and `<ExtractPreview>` build another\n * flow.\n */\nimport {\n Button,\n ErrorState,\n Input,\n Label,\n Modal,\n PendingButton,\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n Textarea,\n type ButtonProps,\n type ImportJob,\n} from \"@karni/ui\";\nimport * as React from \"react\";\nimport { ExtractPreview, type ExtractPreviewSlots } from \"./ExtractPreview\";\nimport { extractRefusal, useExtract } from \"./hooks\";\nimport type { ExtractInput, ExtractResult, ExtractSourceKind } from \"./types\";\n\n/** Experimental. What the `Error` slot receives: why the extraction was refused or failed. */\nexport interface ExtractErrorProps {\n error: unknown;\n resourceLabel: string;\n}\n\nexport interface ExtractButtonSlots extends ExtractPreviewSlots {\n Error: React.ComponentType<ExtractErrorProps>;\n}\n\nexport interface ExtractButtonProps extends Omit<ButtonProps, \"onClick\" | \"onError\"> {\n /** The resource's router prefix (\"products\"). */\n resource: string;\n /** The resource in words, plural (\"products\"). Default: the router prefix. */\n resourceLabel?: string;\n /** The forms offered, in order. Default: text, a web page, a PDF. */\n sources?: readonly ExtractSourceKind[];\n /** Called with the preview once the rows are read. */\n onExtracted?: (result: ExtractResult) => void;\n /** Called once the commit saved the rows. */\n onDone?: (job: ImportJob) => void;\n slots?: Partial<ExtractButtonSlots>;\n}\n\nconst SOURCE_LABELS: Record<ExtractSourceKind, string> = {\n text: \"Text\",\n url: \"Web page\",\n pdf: \"PDF\",\n};\n\nconst SOURCE_WORDS: Record<ExtractSourceKind, string> = {\n text: \"a text\",\n url: \"a web page\",\n pdf: \"a PDF\",\n};\n\n/** \"a text, a web page or a PDF\" for the sources offered. */\nfunction sourceWords(sources: readonly ExtractSourceKind[]): string {\n const words = sources.map((source) => SOURCE_WORDS[source]);\n if (words.length <= 1) return words[0] ?? \"a source\";\n return `${words.slice(0, -1).join(\", \")} or ${words[words.length - 1]}`;\n}\n\nconst REFUSAL_TITLES: Record<string, string> = {\n AI008: \"This resource can't be extracted into\",\n AI009: \"You can't add these rows\",\n AI010: \"This source can't be read\",\n AI011: \"This address can't be fetched\",\n AI012: \"This page can't be read\",\n AI013: \"Your monthly budget is spent\",\n AI014: \"The monthly budget is spent\",\n};\n\n/** The default `Error` slot: an AI refusal in the backend's words, anything else as ErrorState. */\nfunction DefaultExtractError({ error, resourceLabel }: ExtractErrorProps): React.ReactElement {\n const refusal = extractRefusal(error);\n if (refusal === undefined) {\n return (\n <ErrorState\n variant=\"inline\"\n error={error}\n context={{ action: \"extract\", resource: resourceLabel }}\n />\n );\n }\n return (\n <div\n role=\"alert\"\n className=\"rounded-md border border-destructive-border bg-destructive-subtle p-3 text-sm\"\n >\n <p className=\"font-medium text-foreground\">\n {REFUSAL_TITLES[refusal.code] ?? \"The extraction failed\"}\n </p>\n <p className=\"text-muted-foreground\">{refusal.detail}</p>\n </div>\n );\n}\n\ninterface SourceFormProps {\n sources: readonly ExtractSourceKind[];\n pending: boolean;\n onSubmit: (input: ExtractInput) => void;\n}\n\nfunction SourceForm({ sources, pending, onSubmit }: SourceFormProps): React.ReactElement {\n const ids = {\n text: React.useId(),\n url: React.useId(),\n pdf: React.useId(),\n };\n const [kind, setKind] = React.useState<ExtractSourceKind>(sources[0] ?? \"text\");\n const [text, setText] = React.useState(\"\");\n const [url, setUrl] = React.useState(\"\");\n const [file, setFile] = React.useState<File | null>(null);\n\n const submit = (event: React.FormEvent<HTMLFormElement>): void => {\n event.preventDefault();\n if (kind === \"text\") onSubmit({ text });\n else if (kind === \"url\") onSubmit({ url });\n else if (file !== null) onSubmit({ file });\n };\n\n const field = (source: ExtractSourceKind): React.ReactElement => {\n if (source === \"text\") {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={ids.text}>Text to read</Label>\n <Textarea\n id={ids.text}\n rows={8}\n required\n value={text}\n onChange={(event) => setText(event.target.value)}\n />\n </div>\n );\n }\n if (source === \"url\") {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={ids.url}>Address of the page</Label>\n <Input\n id={ids.url}\n type=\"url\"\n required\n placeholder=\"https://\"\n value={url}\n onChange={(event) => setUrl(event.target.value)}\n />\n </div>\n );\n }\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={ids.pdf}>PDF file</Label>\n <Input\n id={ids.pdf}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n className=\"cursor-pointer\"\n onChange={(event) => setFile(event.target.files?.[0] ?? null)}\n />\n </div>\n );\n };\n\n return (\n <form onSubmit={submit} className=\"space-y-3\" aria-label=\"Source to read\">\n {sources.length > 1 ? (\n <Tabs value={kind} onValueChange={(value) => setKind(value as ExtractSourceKind)}>\n <TabsList>\n {sources.map((source) => (\n <TabsTrigger key={source} value={source}>\n {SOURCE_LABELS[source]}\n </TabsTrigger>\n ))}\n </TabsList>\n {sources.map((source) => (\n <TabsContent key={source} value={source}>\n {field(source)}\n </TabsContent>\n ))}\n </Tabs>\n ) : (\n field(kind)\n )}\n <PendingButton\n type=\"submit\"\n pending={pending}\n pendingLabel=\"Reading…\"\n disabled={kind === \"pdf\" && file === null}\n >\n Extract\n </PendingButton>\n </form>\n );\n}\n\n/** Experimental. A button that reads rows from a source into the import preview. */\nexport function ExtractButton(props: ExtractButtonProps): React.ReactElement {\n const {\n resource,\n resourceLabel,\n sources = [\"text\", \"url\", \"pdf\"],\n onExtracted,\n onDone,\n slots,\n children,\n ...buttonProps\n } = props;\n const label = resourceLabel ?? resource;\n const ErrorSlot = slots?.Error ?? DefaultExtractError;\n const [open, setOpen] = React.useState(false);\n const [result, setResult] = React.useState<ExtractResult | undefined>(undefined);\n const extract = useExtract(resource);\n\n const startOver = (): void => {\n setResult(undefined);\n extract.reset();\n };\n\n return (\n <Modal\n open={open}\n onOpenChange={(next) => {\n setOpen(next);\n if (!next) startOver();\n }}\n title={`Extract ${label}`}\n description={`Read ${label} from ${sourceWords(sources)}. Nothing is saved until you commit the preview.`}\n className=\"max-w-3xl\"\n trigger={\n <Button data-karni-role=\"extract-button\" {...buttonProps}>\n {children ?? \"Extract with AI\"}\n </Button>\n }\n >\n {result === undefined ? (\n <div className=\"space-y-3\">\n <SourceForm\n sources={sources}\n pending={extract.isPending}\n onSubmit={(input) =>\n extract.mutate(input, {\n onSuccess: (answer) => {\n setResult(answer);\n onExtracted?.(answer);\n },\n })\n }\n />\n {extract.error !== null && extract.error !== undefined ? (\n <ErrorSlot error={extract.error} resourceLabel={label} />\n ) : null}\n </div>\n ) : (\n <ExtractPreview\n result={result}\n resourceLabel={label}\n onDone={onDone}\n onStartOver={startOver}\n slots={slots}\n />\n )}\n </Modal>\n );\n}\n","/** @karni/ai-ui public barrel: explicit exports only. Experimental. */\nimport { registerAiRoles } from \"./roles\";\n\nexport { ExtractButton } from \"./ExtractButton\";\nexport type { ExtractButtonProps, ExtractButtonSlots, ExtractErrorProps } from \"./ExtractButton\";\n\nexport { ExtractPreview, defaultExtractPreviewSlots, rowFields } from \"./ExtractPreview\";\nexport type {\n ExtractPreviewProps,\n ExtractPreviewSlots,\n ExtractProblemsProps,\n ExtractRowsProps,\n} from \"./ExtractPreview\";\n\nexport { EXTRACT_PATH, extractRefusal, useExtract } from \"./hooks\";\n\nexport type {\n ExtractInput,\n ExtractProblem,\n ExtractRefusal,\n ExtractResult,\n ExtractSourceKind,\n ExtractUsage,\n} from \"./types\";\n\nexport { AI_COMPONENT_ROLES, registerAiRoles } from \"./roles\";\nexport type { ComponentRoleDefinition } from \"./roles\";\n\nregisterAiRoles();\n"],"mappings":"A,isBAUA,IAAakD,EAAyD,CACpE,CACE,KAAM,iBACN,UAAW,gBACX,QAAS,eACT,YACE,uGACJ,CACF,EAKA,SAAgBC,EAAgB,EAAoBnD,EAAkB,CACpE,GAAI,OAAOoD,GAAa,WAAYA,EAAmB,MAAO,GAC9D,IAAMC,EAAaD,EAAqCE,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 +1,395 @@
|
|
|
1
|
+
import * as e from "@karni/ui";
|
|
2
|
+
import { Button as t, EmptyValue as n, ErrorState as r, Input as i, KarniApiError as a, Label as o, Modal as s, PendingButton as c, Tabs as l, TabsContent as u, TabsList as d, TabsTrigger as f, Textarea as p, defaultResourceImportSlots as m, importJobKey as h, isImportInFlight as g, karniKeys as _, useImportActions as v, useImportJob as y, useKarniClient as b } from "@karni/ui";
|
|
3
|
+
import * as x from "react";
|
|
4
|
+
import { jsx as S, jsxs as C } from "react/jsx-runtime";
|
|
5
|
+
import { useMutation as w, useQueryClient as T } from "@tanstack/react-query";
|
|
6
|
+
//#region src/roles.ts
|
|
7
|
+
var E = [{
|
|
8
|
+
role: "extract-button",
|
|
9
|
+
component: "ExtractButton",
|
|
10
|
+
package: "@karni/ai-ui",
|
|
11
|
+
description: "Reads rows of a resource from a text, a web page or a PDF into the import preview, then commits them."
|
|
12
|
+
}];
|
|
13
|
+
function D(t = e) {
|
|
14
|
+
if (typeof t != "object" || !t) return !1;
|
|
15
|
+
let n = t.registerComponentRole;
|
|
16
|
+
if (typeof n != "function") return !1;
|
|
17
|
+
for (let e of E) n(e.role, e);
|
|
18
|
+
return !0;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/ExtractPreview.tsx
|
|
22
|
+
function O(e, t, n) {
|
|
23
|
+
return `${e.toLocaleString()} ${e === 1 ? t : n}`;
|
|
24
|
+
}
|
|
25
|
+
function k(e) {
|
|
26
|
+
return e == null || e === "" ? /* @__PURE__ */ S(n, {}) : Array.isArray(e) ? e.map(String).join(", ") : typeof e == "boolean" ? e ? "Yes" : "No" : typeof e == "object" ? JSON.stringify(e) : String(e);
|
|
27
|
+
}
|
|
28
|
+
function A(e) {
|
|
29
|
+
let t = [];
|
|
30
|
+
for (let n of e) for (let e of Object.keys(n)) t.includes(e) || t.push(e);
|
|
31
|
+
return t;
|
|
32
|
+
}
|
|
33
|
+
function j({ rows: e, fields: t }) {
|
|
34
|
+
return /* @__PURE__ */ S("div", {
|
|
35
|
+
className: "overflow-x-auto rounded-md border border-border",
|
|
36
|
+
children: /* @__PURE__ */ C("table", {
|
|
37
|
+
className: "w-full text-sm",
|
|
38
|
+
children: [
|
|
39
|
+
/* @__PURE__ */ S("caption", {
|
|
40
|
+
className: "px-3 py-2 text-left text-sm font-medium text-foreground",
|
|
41
|
+
children: "Proposed rows"
|
|
42
|
+
}),
|
|
43
|
+
/* @__PURE__ */ S("thead", {
|
|
44
|
+
className: "bg-muted text-left text-xs uppercase text-muted-foreground",
|
|
45
|
+
children: /* @__PURE__ */ C("tr", { children: [/* @__PURE__ */ S("th", {
|
|
46
|
+
scope: "col",
|
|
47
|
+
className: "px-3 py-2 font-medium",
|
|
48
|
+
children: "Row"
|
|
49
|
+
}), t.map((e) => /* @__PURE__ */ S("th", {
|
|
50
|
+
scope: "col",
|
|
51
|
+
className: "px-3 py-2 font-medium",
|
|
52
|
+
children: e
|
|
53
|
+
}, e))] })
|
|
54
|
+
}),
|
|
55
|
+
/* @__PURE__ */ S("tbody", { children: e.map((e, n) => /* @__PURE__ */ C("tr", {
|
|
56
|
+
className: "border-t border-border",
|
|
57
|
+
children: [/* @__PURE__ */ S("th", {
|
|
58
|
+
scope: "row",
|
|
59
|
+
className: "px-3 py-2 text-left font-normal tabular-nums",
|
|
60
|
+
children: n + 1
|
|
61
|
+
}), t.map((t) => /* @__PURE__ */ S("td", {
|
|
62
|
+
className: "px-3 py-2",
|
|
63
|
+
children: k(e[t])
|
|
64
|
+
}, t))]
|
|
65
|
+
}, n)) })
|
|
66
|
+
]
|
|
67
|
+
})
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
var M = {
|
|
71
|
+
schema: "Reading",
|
|
72
|
+
preview: "Preview"
|
|
73
|
+
};
|
|
74
|
+
function N({ problems: e }) {
|
|
75
|
+
return /* @__PURE__ */ S("div", {
|
|
76
|
+
className: "overflow-x-auto rounded-md border border-border",
|
|
77
|
+
children: /* @__PURE__ */ C("table", {
|
|
78
|
+
className: "w-full text-sm",
|
|
79
|
+
children: [
|
|
80
|
+
/* @__PURE__ */ S("caption", {
|
|
81
|
+
className: "px-3 py-2 text-left text-sm font-medium text-foreground",
|
|
82
|
+
children: "Problems"
|
|
83
|
+
}),
|
|
84
|
+
/* @__PURE__ */ S("thead", {
|
|
85
|
+
className: "bg-muted text-left text-xs uppercase text-muted-foreground",
|
|
86
|
+
children: /* @__PURE__ */ C("tr", { children: [
|
|
87
|
+
/* @__PURE__ */ S("th", {
|
|
88
|
+
scope: "col",
|
|
89
|
+
className: "px-3 py-2 font-medium",
|
|
90
|
+
children: "Row"
|
|
91
|
+
}),
|
|
92
|
+
/* @__PURE__ */ S("th", {
|
|
93
|
+
scope: "col",
|
|
94
|
+
className: "px-3 py-2 font-medium",
|
|
95
|
+
children: "Field"
|
|
96
|
+
}),
|
|
97
|
+
/* @__PURE__ */ S("th", {
|
|
98
|
+
scope: "col",
|
|
99
|
+
className: "px-3 py-2 font-medium",
|
|
100
|
+
children: "Problem"
|
|
101
|
+
}),
|
|
102
|
+
/* @__PURE__ */ S("th", {
|
|
103
|
+
scope: "col",
|
|
104
|
+
className: "px-3 py-2 font-medium",
|
|
105
|
+
children: "Found by"
|
|
106
|
+
})
|
|
107
|
+
] })
|
|
108
|
+
}),
|
|
109
|
+
/* @__PURE__ */ S("tbody", { children: e.map((e, t) => /* @__PURE__ */ C("tr", {
|
|
110
|
+
className: "border-t border-border",
|
|
111
|
+
children: [
|
|
112
|
+
/* @__PURE__ */ S("th", {
|
|
113
|
+
scope: "row",
|
|
114
|
+
className: "px-3 py-2 text-left font-normal tabular-nums",
|
|
115
|
+
children: e.row > 0 ? e.row : /* @__PURE__ */ S(n, { label: "every row" })
|
|
116
|
+
}),
|
|
117
|
+
/* @__PURE__ */ S("td", {
|
|
118
|
+
className: "px-3 py-2 font-mono text-xs",
|
|
119
|
+
children: e.field || /* @__PURE__ */ S(n, { label: "the whole row" })
|
|
120
|
+
}),
|
|
121
|
+
/* @__PURE__ */ S("td", {
|
|
122
|
+
className: "px-3 py-2",
|
|
123
|
+
children: e.message
|
|
124
|
+
}),
|
|
125
|
+
/* @__PURE__ */ S("td", {
|
|
126
|
+
className: "px-3 py-2 text-muted-foreground",
|
|
127
|
+
children: M[e.source]
|
|
128
|
+
})
|
|
129
|
+
]
|
|
130
|
+
}, `${e.row}-${e.field}-${t}`)) })
|
|
131
|
+
]
|
|
132
|
+
})
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
var P = {
|
|
136
|
+
Rows: j,
|
|
137
|
+
Problems: N,
|
|
138
|
+
Summary: m.Summary,
|
|
139
|
+
ConfirmCommit: m.ConfirmCommit,
|
|
140
|
+
Progress: m.Progress
|
|
141
|
+
};
|
|
142
|
+
function F({ result: e, resourceLabel: n, onDone: r, onStartOver: i, slots: a }) {
|
|
143
|
+
let o = {
|
|
144
|
+
...P,
|
|
145
|
+
...a
|
|
146
|
+
}, s = n ?? e.resource, c = y(e.resource, e.id).data ?? e.job, { commit: l } = v(e.resource), [u, d] = x.useState(!1), f = c.status === "done", p = c.result ?? e.result, m = x.useMemo(() => A(e.rows), [e.rows]);
|
|
147
|
+
return x.useEffect(() => {
|
|
148
|
+
f && r?.(c);
|
|
149
|
+
}, [f, c.id]), /* @__PURE__ */ C("section", {
|
|
150
|
+
className: "space-y-3",
|
|
151
|
+
"aria-label": "Extraction preview",
|
|
152
|
+
"data-step": c.status,
|
|
153
|
+
children: [
|
|
154
|
+
/* @__PURE__ */ S("p", {
|
|
155
|
+
role: "status",
|
|
156
|
+
className: "text-sm text-muted-foreground",
|
|
157
|
+
children: f ? `Saved to ${s}: ${O((p?.created ?? 0) + (p?.updated ?? 0), "row", "rows")}.` : `Read ${O(e.rows.length, "row", "rows")} from ${e.source.label}. Nothing is saved yet.`
|
|
158
|
+
}),
|
|
159
|
+
e.rows.length > 0 ? /* @__PURE__ */ S(o.Rows, {
|
|
160
|
+
rows: e.rows,
|
|
161
|
+
fields: m
|
|
162
|
+
}) : null,
|
|
163
|
+
g(c) ? /* @__PURE__ */ S(o.Progress, { job: c }) : null,
|
|
164
|
+
p === null ? null : /* @__PURE__ */ S(o.Summary, {
|
|
165
|
+
job: c,
|
|
166
|
+
result: p
|
|
167
|
+
}),
|
|
168
|
+
e.problems.length > 0 && !f ? /* @__PURE__ */ S(o.Problems, { problems: e.problems }) : null,
|
|
169
|
+
/* @__PURE__ */ C("div", {
|
|
170
|
+
className: "flex flex-wrap gap-2",
|
|
171
|
+
children: [f ? null : /* @__PURE__ */ S(t, {
|
|
172
|
+
onClick: () => {
|
|
173
|
+
l.reset(), d(!0);
|
|
174
|
+
},
|
|
175
|
+
disabled: l.isPending || p === null || c.status !== "previewed",
|
|
176
|
+
children: "Commit"
|
|
177
|
+
}), i === void 0 ? null : /* @__PURE__ */ S(t, {
|
|
178
|
+
variant: "outline",
|
|
179
|
+
onClick: i,
|
|
180
|
+
disabled: l.isPending,
|
|
181
|
+
children: "Read another source"
|
|
182
|
+
})]
|
|
183
|
+
}),
|
|
184
|
+
!f && p !== null ? /* @__PURE__ */ S(o.ConfirmCommit, {
|
|
185
|
+
open: u,
|
|
186
|
+
onOpenChange: (e) => {
|
|
187
|
+
l.isPending || d(e);
|
|
188
|
+
},
|
|
189
|
+
job: c,
|
|
190
|
+
result: p,
|
|
191
|
+
resourceLabel: s,
|
|
192
|
+
pending: l.isPending,
|
|
193
|
+
error: l.error,
|
|
194
|
+
onConfirm: () => l.mutate(c.id, { onSuccess: () => d(!1) })
|
|
195
|
+
}) : null
|
|
196
|
+
]
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/hooks.ts
|
|
201
|
+
var I = "/ai/extract/";
|
|
202
|
+
function L(e) {
|
|
203
|
+
if (!(e instanceof a) || typeof e.data != "object" || e.data === null) return;
|
|
204
|
+
let t = e.data, n = t.code, r = t.detail;
|
|
205
|
+
if (typeof n == "string" && /^AI\d{3}$/.test(n) && typeof r == "string") return {
|
|
206
|
+
code: n,
|
|
207
|
+
detail: r
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function R(e) {
|
|
211
|
+
let t = b(), n = T();
|
|
212
|
+
return w({
|
|
213
|
+
mutationFn: (n) => {
|
|
214
|
+
if ("file" in n) {
|
|
215
|
+
let r = new FormData();
|
|
216
|
+
return r.append("resource", e), r.append("file", n.file), t.request(I, {
|
|
217
|
+
method: "POST",
|
|
218
|
+
body: r
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
return t.request(I, {
|
|
222
|
+
method: "POST",
|
|
223
|
+
body: {
|
|
224
|
+
resource: e,
|
|
225
|
+
...n
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
},
|
|
229
|
+
onSuccess: (t) => {
|
|
230
|
+
n.setQueryData(h(e, t.id), t.job), n.invalidateQueries({ queryKey: _.resource("ai") });
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
//#region src/ExtractButton.tsx
|
|
236
|
+
var z = {
|
|
237
|
+
text: "Text",
|
|
238
|
+
url: "Web page",
|
|
239
|
+
pdf: "PDF"
|
|
240
|
+
}, B = {
|
|
241
|
+
text: "a text",
|
|
242
|
+
url: "a web page",
|
|
243
|
+
pdf: "a PDF"
|
|
244
|
+
};
|
|
245
|
+
function V(e) {
|
|
246
|
+
let t = e.map((e) => B[e]);
|
|
247
|
+
return t.length <= 1 ? t[0] ?? "a source" : `${t.slice(0, -1).join(", ")} or ${t[t.length - 1]}`;
|
|
248
|
+
}
|
|
249
|
+
var H = {
|
|
250
|
+
AI008: "This resource can't be extracted into",
|
|
251
|
+
AI009: "You can't add these rows",
|
|
252
|
+
AI010: "This source can't be read",
|
|
253
|
+
AI011: "This address can't be fetched",
|
|
254
|
+
AI012: "This page can't be read",
|
|
255
|
+
AI013: "Your monthly budget is spent",
|
|
256
|
+
AI014: "The monthly budget is spent"
|
|
257
|
+
};
|
|
258
|
+
function U({ error: e, resourceLabel: t }) {
|
|
259
|
+
let n = L(e);
|
|
260
|
+
return n === void 0 ? /* @__PURE__ */ S(r, {
|
|
261
|
+
variant: "inline",
|
|
262
|
+
error: e,
|
|
263
|
+
context: {
|
|
264
|
+
action: "extract",
|
|
265
|
+
resource: t
|
|
266
|
+
}
|
|
267
|
+
}) : /* @__PURE__ */ C("div", {
|
|
268
|
+
role: "alert",
|
|
269
|
+
className: "rounded-md border border-destructive-border bg-destructive-subtle p-3 text-sm",
|
|
270
|
+
children: [/* @__PURE__ */ S("p", {
|
|
271
|
+
className: "font-medium text-foreground",
|
|
272
|
+
children: H[n.code] ?? "The extraction failed"
|
|
273
|
+
}), /* @__PURE__ */ S("p", {
|
|
274
|
+
className: "text-muted-foreground",
|
|
275
|
+
children: n.detail
|
|
276
|
+
})]
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
function W({ sources: e, pending: t, onSubmit: n }) {
|
|
280
|
+
let r = {
|
|
281
|
+
text: x.useId(),
|
|
282
|
+
url: x.useId(),
|
|
283
|
+
pdf: x.useId()
|
|
284
|
+
}, [a, s] = x.useState(e[0] ?? "text"), [m, h] = x.useState(""), [g, _] = x.useState(""), [v, y] = x.useState(null), b = (e) => {
|
|
285
|
+
e.preventDefault(), a === "text" ? n({ text: m }) : a === "url" ? n({ url: g }) : v !== null && n({ file: v });
|
|
286
|
+
}, w = (e) => e === "text" ? /* @__PURE__ */ C("div", {
|
|
287
|
+
className: "grid gap-1.5",
|
|
288
|
+
children: [/* @__PURE__ */ S(o, {
|
|
289
|
+
htmlFor: r.text,
|
|
290
|
+
children: "Text to read"
|
|
291
|
+
}), /* @__PURE__ */ S(p, {
|
|
292
|
+
id: r.text,
|
|
293
|
+
rows: 8,
|
|
294
|
+
required: !0,
|
|
295
|
+
value: m,
|
|
296
|
+
onChange: (e) => h(e.target.value)
|
|
297
|
+
})]
|
|
298
|
+
}) : e === "url" ? /* @__PURE__ */ C("div", {
|
|
299
|
+
className: "grid gap-1.5",
|
|
300
|
+
children: [/* @__PURE__ */ S(o, {
|
|
301
|
+
htmlFor: r.url,
|
|
302
|
+
children: "Address of the page"
|
|
303
|
+
}), /* @__PURE__ */ S(i, {
|
|
304
|
+
id: r.url,
|
|
305
|
+
type: "url",
|
|
306
|
+
required: !0,
|
|
307
|
+
placeholder: "https://",
|
|
308
|
+
value: g,
|
|
309
|
+
onChange: (e) => _(e.target.value)
|
|
310
|
+
})]
|
|
311
|
+
}) : /* @__PURE__ */ C("div", {
|
|
312
|
+
className: "grid gap-1.5",
|
|
313
|
+
children: [/* @__PURE__ */ S(o, {
|
|
314
|
+
htmlFor: r.pdf,
|
|
315
|
+
children: "PDF file"
|
|
316
|
+
}), /* @__PURE__ */ S(i, {
|
|
317
|
+
id: r.pdf,
|
|
318
|
+
type: "file",
|
|
319
|
+
accept: "application/pdf,.pdf",
|
|
320
|
+
className: "cursor-pointer",
|
|
321
|
+
onChange: (e) => y(e.target.files?.[0] ?? null)
|
|
322
|
+
})]
|
|
323
|
+
});
|
|
324
|
+
return /* @__PURE__ */ C("form", {
|
|
325
|
+
onSubmit: b,
|
|
326
|
+
className: "space-y-3",
|
|
327
|
+
"aria-label": "Source to read",
|
|
328
|
+
children: [e.length > 1 ? /* @__PURE__ */ C(l, {
|
|
329
|
+
value: a,
|
|
330
|
+
onValueChange: (e) => s(e),
|
|
331
|
+
children: [/* @__PURE__ */ S(d, { children: e.map((e) => /* @__PURE__ */ S(f, {
|
|
332
|
+
value: e,
|
|
333
|
+
children: z[e]
|
|
334
|
+
}, e)) }), e.map((e) => /* @__PURE__ */ S(u, {
|
|
335
|
+
value: e,
|
|
336
|
+
children: w(e)
|
|
337
|
+
}, e))]
|
|
338
|
+
}) : w(a), /* @__PURE__ */ S(c, {
|
|
339
|
+
type: "submit",
|
|
340
|
+
pending: t,
|
|
341
|
+
pendingLabel: "Reading…",
|
|
342
|
+
disabled: a === "pdf" && v === null,
|
|
343
|
+
children: "Extract"
|
|
344
|
+
})]
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
function G(e) {
|
|
348
|
+
let { resource: n, resourceLabel: r, sources: i = [
|
|
349
|
+
"text",
|
|
350
|
+
"url",
|
|
351
|
+
"pdf"
|
|
352
|
+
], onExtracted: a, onDone: o, slots: c, children: l, ...u } = e, d = r ?? n, f = c?.Error ?? U, [p, m] = x.useState(!1), [h, g] = x.useState(void 0), _ = R(n), v = () => {
|
|
353
|
+
g(void 0), _.reset();
|
|
354
|
+
};
|
|
355
|
+
return /* @__PURE__ */ S(s, {
|
|
356
|
+
open: p,
|
|
357
|
+
onOpenChange: (e) => {
|
|
358
|
+
m(e), e || v();
|
|
359
|
+
},
|
|
360
|
+
title: `Extract ${d}`,
|
|
361
|
+
description: `Read ${d} from ${V(i)}. Nothing is saved until you commit the preview.`,
|
|
362
|
+
className: "max-w-3xl",
|
|
363
|
+
trigger: /* @__PURE__ */ S(t, {
|
|
364
|
+
"data-karni-role": "extract-button",
|
|
365
|
+
...u,
|
|
366
|
+
children: l ?? "Extract with AI"
|
|
367
|
+
}),
|
|
368
|
+
children: h === void 0 ? /* @__PURE__ */ C("div", {
|
|
369
|
+
className: "space-y-3",
|
|
370
|
+
children: [/* @__PURE__ */ S(W, {
|
|
371
|
+
sources: i,
|
|
372
|
+
pending: _.isPending,
|
|
373
|
+
onSubmit: (e) => _.mutate(e, { onSuccess: (e) => {
|
|
374
|
+
g(e), a?.(e);
|
|
375
|
+
} })
|
|
376
|
+
}), _.error !== null && _.error !== void 0 ? /* @__PURE__ */ S(f, {
|
|
377
|
+
error: _.error,
|
|
378
|
+
resourceLabel: d
|
|
379
|
+
}) : null]
|
|
380
|
+
}) : /* @__PURE__ */ S(F, {
|
|
381
|
+
result: h,
|
|
382
|
+
resourceLabel: d,
|
|
383
|
+
onDone: o,
|
|
384
|
+
onStartOver: v,
|
|
385
|
+
slots: c
|
|
386
|
+
})
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
//#endregion
|
|
390
|
+
//#region src/index.ts
|
|
391
|
+
D();
|
|
392
|
+
//#endregion
|
|
393
|
+
export { E as AI_COMPONENT_ROLES, I as EXTRACT_PATH, G as ExtractButton, F as ExtractPreview, P as defaultExtractPreviewSlots, L as extractRefusal, D as registerAiRoles, A as rowFields, R as useExtract };
|
|
394
|
+
|
|
395
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["karniUi","React","AI_COMPONENT_ROLES","registerAiRoles","registry","candidate","\"registerComponentRole\"","definition","plural","count","one","many","cell","value","EmptyValue","rowFields","seen","row","rows","key","DefaultRows","fields","field","index","FOUND_BY","DefaultProblems","problems","problem","defaultExtractPreviewSlots","defaultResourceImportSlots","ExtractPreview","Slots","slots","label","resourceLabel","result","job","useImportJob","useImportActions","confirmOpen","setConfirmOpen","done","counts","onDone","isImportInFlight","Button","commit","onStartOver","open","EXTRACT_PATH","extractRefusal","error","KarniApiError","data","code","\"code\"","detail","\"detail\"","useExtract","client","useKarniClient","queryClient","useQueryClient","useMutation","input","form","resource","importJobKey","karniKeys","SOURCE_LABELS","SOURCE_WORDS","sourceWords","words","sources","source","REFUSAL_TITLES","DefaultExtractError","refusal","ErrorState","SourceForm","ids","kind","setKind","text","setText","url","setUrl","file","setFile","submit","event","onSubmit","Label","Textarea","Input","Tabs","TabsList","TabsTrigger","TabsContent","PendingButton","ExtractButton","buttonProps","props","ErrorSlot","setOpen","setResult","extract","startOver","Modal","next","children","answer","onExtracted"],"sources":["../src/roles.ts","../src/ExtractPreview.tsx","../src/hooks.ts","../src/ExtractButton.tsx","../src/index.ts"],"sourcesContent":["/** Component-role registration, feature-detected on @karni/ui's registry. */\nimport * as karniUi from \"@karni/ui\";\n\nexport interface ComponentRoleDefinition {\n role: string;\n component: string;\n package: string;\n description: string;\n}\n\nexport const AI_COMPONENT_ROLES: readonly ComponentRoleDefinition[] = [\n {\n role: \"extract-button\",\n component: \"ExtractButton\",\n package: \"@karni/ai-ui\",\n description:\n \"Reads rows of a resource from a text, a web page or a PDF into the import preview, then commits them.\",\n },\n];\n\ntype RegisterComponentRole = (role: string, definition: ComponentRoleDefinition) => void;\n\n/** Experimental. Registers the package's components in @karni/ui's role registry, if any. */\nexport function registerAiRoles(registry: unknown = karniUi): boolean {\n if (typeof registry !== \"object\" || registry === null) return false;\n const candidate = (registry as Record<string, unknown>)[\"registerComponentRole\"];\n if (typeof candidate !== \"function\") return false;\n for (const definition of AI_COMPONENT_ROLES) {\n (candidate as RegisterComponentRole)(definition.role, definition);\n }\n return true;\n}\n","/**\n * <ExtractPreview>: the import preview of an extraction, and its commit. Experimental.\n *\n * Shows the proposed rows, a problem per field (found while reading the\n * answer, or by the import's dry run), the preview's counts, and Commit,\n * which confirms through `@karni/ui`'s `useImportActions(resource).commit`:\n * the import's own commit path. Nothing is saved before that.\n *\n * The counts and the confirmation reuse `@karni/ui`'s import slots\n * (`defaultResourceImportSlots.Summary` and `.ConfirmCommit`), so an\n * extraction reads like a file import. Escape hatch: replace any part with\n * `slots` (Rows, Problems, Summary, ConfirmCommit, Progress).\n */\nimport {\n Button,\n EmptyValue,\n defaultResourceImportSlots,\n isImportInFlight,\n useImportActions,\n useImportJob,\n type ImportConfirmProps,\n type ImportJob,\n type ImportProgressProps,\n type ImportSummaryProps,\n} from \"@karni/ui\";\nimport * as React from \"react\";\nimport type { ExtractProblem, ExtractResult } from \"./types\";\n\n/** Experimental. What the `Rows` slot receives: the proposed rows and their fields. */\nexport interface ExtractRowsProps {\n rows: ReadonlyArray<Record<string, unknown>>;\n fields: readonly string[];\n}\n\n/** Experimental. What the `Problems` slot receives: one problem per field, rows from 1. */\nexport interface ExtractProblemsProps {\n problems: readonly ExtractProblem[];\n}\n\n/** Experimental. The replaceable parts of ExtractPreview. */\nexport interface ExtractPreviewSlots {\n Rows: React.ComponentType<ExtractRowsProps>;\n Problems: React.ComponentType<ExtractProblemsProps>;\n Summary: React.ComponentType<ImportSummaryProps>;\n ConfirmCommit: React.ComponentType<ImportConfirmProps>;\n /** A preview or commit running in Celery (more rows than KARNI_IMPORT_INLINE_ROWS). */\n Progress: React.ComponentType<ImportProgressProps>;\n}\n\nexport interface ExtractPreviewProps {\n /** The answer of `useExtract`. */\n result: ExtractResult;\n /** The resource in words, plural (\"products\"). Default: the router prefix. */\n resourceLabel?: string;\n /** Called once the commit saved the rows (the job is `done`). */\n onDone?: (job: ImportJob) => void;\n /** Shown as \"Read another source\" when given. */\n onStartOver?: () => void;\n slots?: Partial<ExtractPreviewSlots>;\n}\n\nfunction plural(count: number, one: string, many: string): string {\n return `${count.toLocaleString()} ${count === 1 ? one : many}`;\n}\n\nfunction cell(value: unknown): React.ReactNode {\n if (value === undefined || value === null || value === \"\") return <EmptyValue />;\n if (Array.isArray(value)) return value.map(String).join(\", \");\n if (typeof value === \"boolean\") return value ? \"Yes\" : \"No\";\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value);\n}\n\n/** Experimental. The fields the rows use, in the order they first appear. */\nexport function rowFields(rows: ReadonlyArray<Record<string, unknown>>): string[] {\n const seen: string[] = [];\n for (const row of rows) {\n for (const key of Object.keys(row)) if (!seen.includes(key)) seen.push(key);\n }\n return seen;\n}\n\nfunction DefaultRows({ rows, fields }: ExtractRowsProps): React.ReactElement {\n return (\n <div className=\"overflow-x-auto rounded-md border border-border\">\n <table className=\"w-full text-sm\">\n <caption className=\"px-3 py-2 text-left text-sm font-medium text-foreground\">\n Proposed rows\n </caption>\n <thead className=\"bg-muted text-left text-xs uppercase text-muted-foreground\">\n <tr>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Row\n </th>\n {fields.map((field) => (\n <th key={field} scope=\"col\" className=\"px-3 py-2 font-medium\">\n {field}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {rows.map((row, index) => (\n <tr key={index} className=\"border-t border-border\">\n <th scope=\"row\" className=\"px-3 py-2 text-left font-normal tabular-nums\">\n {index + 1}\n </th>\n {fields.map((field) => (\n <td key={field} className=\"px-3 py-2\">\n {cell(row[field])}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\nconst FOUND_BY: Record<ExtractProblem[\"source\"], string> = {\n schema: \"Reading\",\n preview: \"Preview\",\n};\n\nfunction DefaultProblems({ problems }: ExtractProblemsProps): React.ReactElement {\n return (\n <div className=\"overflow-x-auto rounded-md border border-border\">\n <table className=\"w-full text-sm\">\n <caption className=\"px-3 py-2 text-left text-sm font-medium text-foreground\">\n Problems\n </caption>\n <thead className=\"bg-muted text-left text-xs uppercase text-muted-foreground\">\n <tr>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Row\n </th>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Field\n </th>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Problem\n </th>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Found by\n </th>\n </tr>\n </thead>\n <tbody>\n {problems.map((problem, index) => (\n <tr key={`${problem.row}-${problem.field}-${index}`} className=\"border-t border-border\">\n <th scope=\"row\" className=\"px-3 py-2 text-left font-normal tabular-nums\">\n {problem.row > 0 ? problem.row : <EmptyValue label=\"every row\" />}\n </th>\n <td className=\"px-3 py-2 font-mono text-xs\">\n {problem.field || <EmptyValue label=\"the whole row\" />}\n </td>\n <td className=\"px-3 py-2\">{problem.message}</td>\n <td className=\"px-3 py-2 text-muted-foreground\">{FOUND_BY[problem.source]}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\n/** Experimental. Karni's own slots, exported so a project can wrap one instead of rewriting it. */\nexport const defaultExtractPreviewSlots: ExtractPreviewSlots = {\n Rows: DefaultRows,\n Problems: DefaultProblems,\n Summary: defaultResourceImportSlots.Summary,\n ConfirmCommit: defaultResourceImportSlots.ConfirmCommit,\n Progress: defaultResourceImportSlots.Progress,\n};\n\n/** Experimental. The preview of an extraction, with the import's own commit. */\nexport function ExtractPreview({\n result,\n resourceLabel,\n onDone,\n onStartOver,\n slots,\n}: ExtractPreviewProps): React.ReactElement {\n const Slots: ExtractPreviewSlots = { ...defaultExtractPreviewSlots, ...slots };\n const label = resourceLabel ?? result.resource;\n const jobQuery = useImportJob(result.resource, result.id);\n const job = jobQuery.data ?? result.job;\n const { commit } = useImportActions(result.resource);\n const [confirmOpen, setConfirmOpen] = React.useState(false);\n const done = job.status === \"done\";\n const counts = job.result ?? result.result;\n const fields = React.useMemo(() => rowFields(result.rows), [result.rows]);\n\n React.useEffect(() => {\n if (done) onDone?.(job);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- fire once per completion\n }, [done, job.id]);\n\n return (\n <section className=\"space-y-3\" aria-label=\"Extraction preview\" data-step={job.status}>\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n {done\n ? `Saved to ${label}: ${plural(\n (counts?.created ?? 0) + (counts?.updated ?? 0),\n \"row\",\n \"rows\",\n )}.`\n : `Read ${plural(result.rows.length, \"row\", \"rows\")} from ${result.source.label}. Nothing is saved yet.`}\n </p>\n {result.rows.length > 0 ? <Slots.Rows rows={result.rows} fields={fields} /> : null}\n {isImportInFlight(job) ? <Slots.Progress job={job} /> : null}\n {counts !== null ? <Slots.Summary job={job} result={counts} /> : null}\n {result.problems.length > 0 && !done ? <Slots.Problems problems={result.problems} /> : null}\n <div className=\"flex flex-wrap gap-2\">\n {done ? null : (\n <Button\n onClick={() => {\n commit.reset();\n setConfirmOpen(true);\n }}\n disabled={commit.isPending || counts === null || job.status !== \"previewed\"}\n >\n Commit\n </Button>\n )}\n {onStartOver !== undefined ? (\n <Button variant=\"outline\" onClick={onStartOver} disabled={commit.isPending}>\n Read another source\n </Button>\n ) : null}\n </div>\n {!done && counts !== null ? (\n <Slots.ConfirmCommit\n open={confirmOpen}\n onOpenChange={(open) => {\n if (!commit.isPending) setConfirmOpen(open);\n }}\n job={job}\n result={counts}\n resourceLabel={label}\n pending={commit.isPending}\n error={commit.error}\n onConfirm={() => commit.mutate(job.id, { onSuccess: () => setConfirmOpen(false) })}\n />\n ) : null}\n </section>\n );\n}\n","/**\n * `useExtract(resource)`: a mutation that posts one source to `POST /api/ai/extract/`\n * and resolves with the import preview of the rows read from it. Experimental.\n *\n * Nothing is saved: confirm the preview with `@karni/ui`'s\n * `useImportActions(resource).commit` (the import's own commit). The answer's\n * import job is put in `@karni/ui`'s import job cache, so `useImportJob(resource, id)`\n * has it without a request.\n */\nimport { importJobKey, KarniApiError, karniKeys, useKarniClient } from \"@karni/ui\";\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport type { ExtractInput, ExtractRefusal, ExtractResult } from \"./types\";\n\n/** Experimental. The extraction endpoint, relative to the client's base URL (it carries `/api`). */\nexport const EXTRACT_PATH = \"/ai/extract/\";\n\n/** Experimental. The refusal an extraction answered with (`{code, detail}`), else undefined. */\nexport function extractRefusal(error: unknown): ExtractRefusal | undefined {\n if (!(error instanceof KarniApiError) || typeof error.data !== \"object\" || error.data === null) {\n return undefined;\n }\n const data = error.data as Record<string, unknown>;\n const code = data[\"code\"];\n const detail = data[\"detail\"];\n if (typeof code === \"string\" && /^AI\\d{3}$/.test(code) && typeof detail === \"string\") {\n return { code, detail };\n }\n return undefined;\n}\n\n/** Experimental. Posts one source for `resource` (a router prefix) and resolves with the preview. */\nexport function useExtract(\n resource: string,\n): UseMutationResult<ExtractResult, unknown, ExtractInput> {\n const client = useKarniClient();\n const queryClient = useQueryClient();\n return useMutation<ExtractResult, unknown, ExtractInput>({\n mutationFn: (input) => {\n if (\"file\" in input) {\n const form = new FormData();\n form.append(\"resource\", resource);\n form.append(\"file\", input.file);\n return client.request<ExtractResult>(EXTRACT_PATH, { method: \"POST\", body: form });\n }\n return client.request<ExtractResult>(EXTRACT_PATH, {\n method: \"POST\",\n body: { resource, ...input },\n });\n },\n onSuccess: (result) => {\n queryClient.setQueryData(importJobKey(resource, result.id), result.job);\n // The caller's usage list (GET /api/ai/) has one more call.\n void queryClient.invalidateQueries({ queryKey: karniKeys.resource(\"ai\") });\n },\n });\n}\n","/**\n * <ExtractButton>: read rows of a resource from a text, a web page or a PDF. Experimental.\n *\n * The button opens a dialog with one form per source. Extract posts it to\n * `POST /api/ai/extract/` (`useExtract`) and the dialog then shows the\n * import preview of the rows (`<ExtractPreview>`). Commit saves them through\n * the import's own commit, after the same confirmation a file import asks\n * for. Nothing is saved before.\n *\n * The backend decides everything that matters: who may extract into the\n * resource, which fields the model fills, what each row's problems are. A\n * refusal (an AI code: the source, the URL, the budget) is shown in the\n * backend's words.\n *\n * Escape hatches: every `@karni/ui` Button prop passes through to the\n * trigger. `sources` limits the forms. `slots` replaces the error display\n * and the preview's parts. `useExtract` and `<ExtractPreview>` build another\n * flow.\n */\nimport {\n Button,\n ErrorState,\n Input,\n Label,\n Modal,\n PendingButton,\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n Textarea,\n type ButtonProps,\n type ImportJob,\n} from \"@karni/ui\";\nimport * as React from \"react\";\nimport { ExtractPreview, type ExtractPreviewSlots } from \"./ExtractPreview\";\nimport { extractRefusal, useExtract } from \"./hooks\";\nimport type { ExtractInput, ExtractResult, ExtractSourceKind } from \"./types\";\n\n/** Experimental. What the `Error` slot receives: why the extraction was refused or failed. */\nexport interface ExtractErrorProps {\n error: unknown;\n resourceLabel: string;\n}\n\nexport interface ExtractButtonSlots extends ExtractPreviewSlots {\n Error: React.ComponentType<ExtractErrorProps>;\n}\n\nexport interface ExtractButtonProps extends Omit<ButtonProps, \"onClick\" | \"onError\"> {\n /** The resource's router prefix (\"products\"). */\n resource: string;\n /** The resource in words, plural (\"products\"). Default: the router prefix. */\n resourceLabel?: string;\n /** The forms offered, in order. Default: text, a web page, a PDF. */\n sources?: readonly ExtractSourceKind[];\n /** Called with the preview once the rows are read. */\n onExtracted?: (result: ExtractResult) => void;\n /** Called once the commit saved the rows. */\n onDone?: (job: ImportJob) => void;\n slots?: Partial<ExtractButtonSlots>;\n}\n\nconst SOURCE_LABELS: Record<ExtractSourceKind, string> = {\n text: \"Text\",\n url: \"Web page\",\n pdf: \"PDF\",\n};\n\nconst SOURCE_WORDS: Record<ExtractSourceKind, string> = {\n text: \"a text\",\n url: \"a web page\",\n pdf: \"a PDF\",\n};\n\n/** \"a text, a web page or a PDF\" for the sources offered. */\nfunction sourceWords(sources: readonly ExtractSourceKind[]): string {\n const words = sources.map((source) => SOURCE_WORDS[source]);\n if (words.length <= 1) return words[0] ?? \"a source\";\n return `${words.slice(0, -1).join(\", \")} or ${words[words.length - 1]}`;\n}\n\nconst REFUSAL_TITLES: Record<string, string> = {\n AI008: \"This resource can't be extracted into\",\n AI009: \"You can't add these rows\",\n AI010: \"This source can't be read\",\n AI011: \"This address can't be fetched\",\n AI012: \"This page can't be read\",\n AI013: \"Your monthly budget is spent\",\n AI014: \"The monthly budget is spent\",\n};\n\n/** The default `Error` slot: an AI refusal in the backend's words, anything else as ErrorState. */\nfunction DefaultExtractError({ error, resourceLabel }: ExtractErrorProps): React.ReactElement {\n const refusal = extractRefusal(error);\n if (refusal === undefined) {\n return (\n <ErrorState\n variant=\"inline\"\n error={error}\n context={{ action: \"extract\", resource: resourceLabel }}\n />\n );\n }\n return (\n <div\n role=\"alert\"\n className=\"rounded-md border border-destructive-border bg-destructive-subtle p-3 text-sm\"\n >\n <p className=\"font-medium text-foreground\">\n {REFUSAL_TITLES[refusal.code] ?? \"The extraction failed\"}\n </p>\n <p className=\"text-muted-foreground\">{refusal.detail}</p>\n </div>\n );\n}\n\ninterface SourceFormProps {\n sources: readonly ExtractSourceKind[];\n pending: boolean;\n onSubmit: (input: ExtractInput) => void;\n}\n\nfunction SourceForm({ sources, pending, onSubmit }: SourceFormProps): React.ReactElement {\n const ids = {\n text: React.useId(),\n url: React.useId(),\n pdf: React.useId(),\n };\n const [kind, setKind] = React.useState<ExtractSourceKind>(sources[0] ?? \"text\");\n const [text, setText] = React.useState(\"\");\n const [url, setUrl] = React.useState(\"\");\n const [file, setFile] = React.useState<File | null>(null);\n\n const submit = (event: React.FormEvent<HTMLFormElement>): void => {\n event.preventDefault();\n if (kind === \"text\") onSubmit({ text });\n else if (kind === \"url\") onSubmit({ url });\n else if (file !== null) onSubmit({ file });\n };\n\n const field = (source: ExtractSourceKind): React.ReactElement => {\n if (source === \"text\") {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={ids.text}>Text to read</Label>\n <Textarea\n id={ids.text}\n rows={8}\n required\n value={text}\n onChange={(event) => setText(event.target.value)}\n />\n </div>\n );\n }\n if (source === \"url\") {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={ids.url}>Address of the page</Label>\n <Input\n id={ids.url}\n type=\"url\"\n required\n placeholder=\"https://\"\n value={url}\n onChange={(event) => setUrl(event.target.value)}\n />\n </div>\n );\n }\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={ids.pdf}>PDF file</Label>\n <Input\n id={ids.pdf}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n className=\"cursor-pointer\"\n onChange={(event) => setFile(event.target.files?.[0] ?? null)}\n />\n </div>\n );\n };\n\n return (\n <form onSubmit={submit} className=\"space-y-3\" aria-label=\"Source to read\">\n {sources.length > 1 ? (\n <Tabs value={kind} onValueChange={(value) => setKind(value as ExtractSourceKind)}>\n <TabsList>\n {sources.map((source) => (\n <TabsTrigger key={source} value={source}>\n {SOURCE_LABELS[source]}\n </TabsTrigger>\n ))}\n </TabsList>\n {sources.map((source) => (\n <TabsContent key={source} value={source}>\n {field(source)}\n </TabsContent>\n ))}\n </Tabs>\n ) : (\n field(kind)\n )}\n <PendingButton\n type=\"submit\"\n pending={pending}\n pendingLabel=\"Reading…\"\n disabled={kind === \"pdf\" && file === null}\n >\n Extract\n </PendingButton>\n </form>\n );\n}\n\n/** Experimental. A button that reads rows from a source into the import preview. */\nexport function ExtractButton(props: ExtractButtonProps): React.ReactElement {\n const {\n resource,\n resourceLabel,\n sources = [\"text\", \"url\", \"pdf\"],\n onExtracted,\n onDone,\n slots,\n children,\n ...buttonProps\n } = props;\n const label = resourceLabel ?? resource;\n const ErrorSlot = slots?.Error ?? DefaultExtractError;\n const [open, setOpen] = React.useState(false);\n const [result, setResult] = React.useState<ExtractResult | undefined>(undefined);\n const extract = useExtract(resource);\n\n const startOver = (): void => {\n setResult(undefined);\n extract.reset();\n };\n\n return (\n <Modal\n open={open}\n onOpenChange={(next) => {\n setOpen(next);\n if (!next) startOver();\n }}\n title={`Extract ${label}`}\n description={`Read ${label} from ${sourceWords(sources)}. Nothing is saved until you commit the preview.`}\n className=\"max-w-3xl\"\n trigger={\n <Button data-karni-role=\"extract-button\" {...buttonProps}>\n {children ?? \"Extract with AI\"}\n </Button>\n }\n >\n {result === undefined ? (\n <div className=\"space-y-3\">\n <SourceForm\n sources={sources}\n pending={extract.isPending}\n onSubmit={(input) =>\n extract.mutate(input, {\n onSuccess: (answer) => {\n setResult(answer);\n onExtracted?.(answer);\n },\n })\n }\n />\n {extract.error !== null && extract.error !== undefined ? (\n <ErrorSlot error={extract.error} resourceLabel={label} />\n ) : null}\n </div>\n ) : (\n <ExtractPreview\n result={result}\n resourceLabel={label}\n onDone={onDone}\n onStartOver={startOver}\n slots={slots}\n />\n )}\n </Modal>\n );\n}\n","/** @karni/ai-ui public barrel: explicit exports only. Experimental. */\nimport { registerAiRoles } from \"./roles\";\n\nexport { ExtractButton } from \"./ExtractButton\";\nexport type { ExtractButtonProps, ExtractButtonSlots, ExtractErrorProps } from \"./ExtractButton\";\n\nexport { ExtractPreview, defaultExtractPreviewSlots, rowFields } from \"./ExtractPreview\";\nexport type {\n ExtractPreviewProps,\n ExtractPreviewSlots,\n ExtractProblemsProps,\n ExtractRowsProps,\n} from \"./ExtractPreview\";\n\nexport { EXTRACT_PATH, extractRefusal, useExtract } from \"./hooks\";\n\nexport type {\n ExtractInput,\n ExtractProblem,\n ExtractRefusal,\n ExtractResult,\n ExtractSourceKind,\n ExtractUsage,\n} from \"./types\";\n\nexport { AI_COMPONENT_ROLES, registerAiRoles } from \"./roles\";\nexport type { ComponentRoleDefinition } from \"./roles\";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,aACA,GAAGC,MACDC,GACErE,IAAQC,KAAiBgC,GACzBqC,IAAYvE,GAAO,SAAS4C,GAC5B,CAAC5B,GAAMwD,KAAWvG,EAAM,SAAS,EAAK,GACtC,CAACkC,GAAQsE,KAAaxG,EAAM,SAAoC,KAAA,CAAS,GACzEyG,IAAUhD,EAAWQ,CAAQ,GAE7ByC,UAAwB;EAE5B,AADAF,EAAU,KAAA,CAAS,GACnBC,EAAQ,MAAM;CAChB;CAEA,OACE,kBAACE,GAAD;EACQ;EACN,eAAe,MAAS;GAEtB,AADAJ,EAAQK,CAAI,GACPA,KAAMF,EAAU;EACvB;EACA,OAAO,WAAW1E;EAClB,aAAa,QAAQA,EAAM,QAAQsC,EAAYE,CAAO,EAAE;EACxD,WAAU;EACV,SACE,kBAAC5B,GAAD;GAAQ,mBAAgB;GAAiB,GAAIwD;GAC1C,UAAAS,KAAY;EACP,CAAA;EAGT,UAAA3E,MAAW,KAAA,IACV,kBAAC,OAAD;GAAK,WAAU;GAAf,UAAA,CACE,kBAAC4C,GAAD;IACW;IACT,SAAS2B,EAAQ;IACjB,WAAW,MACTA,EAAQ,OAAO1C,GAAO,EACpB,YAAY,MAAW;KAErB,AADAyC,EAAUM,CAAM,GAChBC,IAAcD,CAAM;IACtB,EACF,CAAC;GAEJ,CAAA,GACAL,EAAQ,UAAU,QAAQA,EAAQ,UAAU,KAAA,IAC3C,kBAACH,GAAD;IAAW,OAAOG,EAAQ;IAAO,eAAezE;GAAQ,CAAA,IACtD,IACD;EAEL,CAAA,IAAA,kBAACH,GAAD;GACU;GACR,eAAeG;GACP;GACR,aAAa0E;GACN;EACR,CAAA;CAEE,CAAA;AAEX;;;ACjQAxG,EAAgB"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ButtonProps, ImportJob } from '@karni/ui';
|
|
2
|
+
import { ExtractPreviewSlots } from './ExtractPreview';
|
|
3
|
+
import { ExtractResult, ExtractSourceKind } from './types';
|
|
4
|
+
import * as React from "react";
|
|
5
|
+
/** Experimental. What the `Error` slot receives: why the extraction was refused or failed. */
|
|
6
|
+
export interface ExtractErrorProps {
|
|
7
|
+
error: unknown;
|
|
8
|
+
resourceLabel: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ExtractButtonSlots extends ExtractPreviewSlots {
|
|
11
|
+
Error: React.ComponentType<ExtractErrorProps>;
|
|
12
|
+
}
|
|
13
|
+
export interface ExtractButtonProps extends Omit<ButtonProps, "onClick" | "onError"> {
|
|
14
|
+
/** The resource's router prefix ("products"). */
|
|
15
|
+
resource: string;
|
|
16
|
+
/** The resource in words, plural ("products"). Default: the router prefix. */
|
|
17
|
+
resourceLabel?: string;
|
|
18
|
+
/** The forms offered, in order. Default: text, a web page, a PDF. */
|
|
19
|
+
sources?: readonly ExtractSourceKind[];
|
|
20
|
+
/** Called with the preview once the rows are read. */
|
|
21
|
+
onExtracted?: (result: ExtractResult) => void;
|
|
22
|
+
/** Called once the commit saved the rows. */
|
|
23
|
+
onDone?: (job: ImportJob) => void;
|
|
24
|
+
slots?: Partial<ExtractButtonSlots>;
|
|
25
|
+
}
|
|
26
|
+
/** Experimental. A button that reads rows from a source into the import preview. */
|
|
27
|
+
export declare function ExtractButton(props: ExtractButtonProps): React.ReactElement;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { ImportConfirmProps, ImportJob, ImportProgressProps, ImportSummaryProps } from '@karni/ui';
|
|
2
|
+
import { ExtractProblem, ExtractResult } from './types';
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
/** Experimental. What the `Rows` slot receives: the proposed rows and their fields. */
|
|
5
|
+
export interface ExtractRowsProps {
|
|
6
|
+
rows: ReadonlyArray<Record<string, unknown>>;
|
|
7
|
+
fields: readonly string[];
|
|
8
|
+
}
|
|
9
|
+
/** Experimental. What the `Problems` slot receives: one problem per field, rows from 1. */
|
|
10
|
+
export interface ExtractProblemsProps {
|
|
11
|
+
problems: readonly ExtractProblem[];
|
|
12
|
+
}
|
|
13
|
+
/** Experimental. The replaceable parts of ExtractPreview. */
|
|
14
|
+
export interface ExtractPreviewSlots {
|
|
15
|
+
Rows: React.ComponentType<ExtractRowsProps>;
|
|
16
|
+
Problems: React.ComponentType<ExtractProblemsProps>;
|
|
17
|
+
Summary: React.ComponentType<ImportSummaryProps>;
|
|
18
|
+
ConfirmCommit: React.ComponentType<ImportConfirmProps>;
|
|
19
|
+
/** A preview or commit running in Celery (more rows than KARNI_IMPORT_INLINE_ROWS). */
|
|
20
|
+
Progress: React.ComponentType<ImportProgressProps>;
|
|
21
|
+
}
|
|
22
|
+
export interface ExtractPreviewProps {
|
|
23
|
+
/** The answer of `useExtract`. */
|
|
24
|
+
result: ExtractResult;
|
|
25
|
+
/** The resource in words, plural ("products"). Default: the router prefix. */
|
|
26
|
+
resourceLabel?: string;
|
|
27
|
+
/** Called once the commit saved the rows (the job is `done`). */
|
|
28
|
+
onDone?: (job: ImportJob) => void;
|
|
29
|
+
/** Shown as "Read another source" when given. */
|
|
30
|
+
onStartOver?: () => void;
|
|
31
|
+
slots?: Partial<ExtractPreviewSlots>;
|
|
32
|
+
}
|
|
33
|
+
/** Experimental. The fields the rows use, in the order they first appear. */
|
|
34
|
+
export declare function rowFields(rows: ReadonlyArray<Record<string, unknown>>): string[];
|
|
35
|
+
/** Experimental. Karni's own slots, exported so a project can wrap one instead of rewriting it. */
|
|
36
|
+
export declare const defaultExtractPreviewSlots: ExtractPreviewSlots;
|
|
37
|
+
/** Experimental. The preview of an extraction, with the import's own commit. */
|
|
38
|
+
export declare function ExtractPreview({ result, resourceLabel, onDone, onStartOver, slots, }: ExtractPreviewProps): React.ReactElement;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { UseMutationResult } from '@tanstack/react-query';
|
|
2
|
+
import { ExtractInput, ExtractRefusal, ExtractResult } from './types';
|
|
3
|
+
/** Experimental. The extraction endpoint, relative to the client's base URL (it carries `/api`). */
|
|
4
|
+
export declare const EXTRACT_PATH = "/ai/extract/";
|
|
5
|
+
/** Experimental. The refusal an extraction answered with (`{code, detail}`), else undefined. */
|
|
6
|
+
export declare function extractRefusal(error: unknown): ExtractRefusal | undefined;
|
|
7
|
+
/** Experimental. Posts one source for `resource` (a router prefix) and resolves with the preview. */
|
|
8
|
+
export declare function useExtract(resource: string): UseMutationResult<ExtractResult, unknown, ExtractInput>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { ExtractButton } from './ExtractButton';
|
|
2
|
+
export type { ExtractButtonProps, ExtractButtonSlots, ExtractErrorProps } from './ExtractButton';
|
|
3
|
+
export { ExtractPreview, defaultExtractPreviewSlots, rowFields } from './ExtractPreview';
|
|
4
|
+
export type { ExtractPreviewProps, ExtractPreviewSlots, ExtractProblemsProps, ExtractRowsProps, } from './ExtractPreview';
|
|
5
|
+
export { EXTRACT_PATH, extractRefusal, useExtract } from './hooks';
|
|
6
|
+
export type { ExtractInput, ExtractProblem, ExtractRefusal, ExtractResult, ExtractSourceKind, ExtractUsage, } from './types';
|
|
7
|
+
export { AI_COMPONENT_ROLES, registerAiRoles } from './roles';
|
|
8
|
+
export type { ComponentRoleDefinition } from './roles';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface ComponentRoleDefinition {
|
|
2
|
+
role: string;
|
|
3
|
+
component: string;
|
|
4
|
+
package: string;
|
|
5
|
+
description: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const AI_COMPONENT_ROLES: readonly ComponentRoleDefinition[];
|
|
8
|
+
/** Experimental. Registers the package's components in @karni/ui's role registry, if any. */
|
|
9
|
+
export declare function registerAiRoles(registry?: unknown): boolean;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { ImportJob, ImportResult } from '@karni/ui';
|
|
2
|
+
/** Experimental. Where the rows were read from. */
|
|
3
|
+
export type ExtractSourceKind = "text" | "url" | "pdf";
|
|
4
|
+
/** Experimental. What to read: exactly one of the three. */
|
|
5
|
+
export type ExtractInput = {
|
|
6
|
+
text: string;
|
|
7
|
+
} | {
|
|
8
|
+
url: string;
|
|
9
|
+
} | {
|
|
10
|
+
file: File;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Experimental. One thing wrong with one proposed row. `row` is the row's position in `rows`, from 1.
|
|
14
|
+
* `source` is `schema` (the answer did not fit the field) or `preview` (the import refused it).
|
|
15
|
+
*/
|
|
16
|
+
export interface ExtractProblem {
|
|
17
|
+
row: number;
|
|
18
|
+
field: string;
|
|
19
|
+
message: string;
|
|
20
|
+
source: "schema" | "preview";
|
|
21
|
+
}
|
|
22
|
+
/** Experimental. The tokens and cost of the provider call (`cost` null: no price). */
|
|
23
|
+
export interface ExtractUsage {
|
|
24
|
+
provider: string;
|
|
25
|
+
model: string;
|
|
26
|
+
input_tokens: number;
|
|
27
|
+
output_tokens: number;
|
|
28
|
+
cost: string | null;
|
|
29
|
+
}
|
|
30
|
+
/** Experimental. The answer of `POST /api/ai/extract/` (201). */
|
|
31
|
+
export interface ExtractResult {
|
|
32
|
+
/** The import job's id: commit it to save the rows. */
|
|
33
|
+
id: string;
|
|
34
|
+
resource: string;
|
|
35
|
+
source: {
|
|
36
|
+
kind: ExtractSourceKind;
|
|
37
|
+
label: string;
|
|
38
|
+
};
|
|
39
|
+
status: ImportJob["status"];
|
|
40
|
+
/** The proposed rows, field to value, as the preview read them. */
|
|
41
|
+
rows: Array<Record<string, unknown>>;
|
|
42
|
+
problems: ExtractProblem[];
|
|
43
|
+
/** The preview's counts: what the commit will do. */
|
|
44
|
+
result: ImportResult | null;
|
|
45
|
+
/** The import's own commit path, relative to the site. */
|
|
46
|
+
commit: string;
|
|
47
|
+
/** The import job, as `GET /api/<resource>/import/<id>/` answers it. */
|
|
48
|
+
job: ImportJob;
|
|
49
|
+
usage: ExtractUsage;
|
|
50
|
+
}
|
|
51
|
+
/** Experimental. The body of a refused extraction: an AI code (AI008, AI010...) and why. */
|
|
52
|
+
export interface ExtractRefusal {
|
|
53
|
+
code: string;
|
|
54
|
+
detail: string;
|
|
55
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,93 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@karni/ai-ui",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "React components for the Karni AI extraction module: ExtractButton and the useExtract hook. Karni is an open-source Django + React framework for building with AI coding agents. Your agent writes only your domain. The API, admin, permissions and React screens come from a package you upgrade, not code it rewrites in each project. One rule set covers every coding agent. The build fails when an agent hand-writes what Karni ships.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"react",
|
|
7
|
+
"django",
|
|
8
|
+
"ai",
|
|
9
|
+
"extraction",
|
|
10
|
+
"llm",
|
|
11
|
+
"import",
|
|
12
|
+
"karni"
|
|
13
|
+
],
|
|
14
|
+
"license": "Apache-2.0",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/cbsshekhawat18-lab/karni.git",
|
|
18
|
+
"directory": "modules/karni-ai/ui"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/cbsshekhawat18-lab/karni/tree/main/modules/karni-ai/ui#readme",
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/cbsshekhawat18-lab/karni/issues"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=20"
|
|
31
|
+
},
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/src/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js",
|
|
36
|
+
"require": "./dist/index.cjs"
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"main": "./dist/index.cjs",
|
|
41
|
+
"module": "./dist/index.js",
|
|
42
|
+
"types": "./dist/src/index.d.ts",
|
|
43
|
+
"scripts": {
|
|
44
|
+
"dev": "vite build --watch",
|
|
45
|
+
"build": "tsc --noEmit && vite build",
|
|
46
|
+
"test": "vitest run",
|
|
47
|
+
"test:watch": "vitest",
|
|
48
|
+
"lint": "eslint . --ext .ts,.tsx,.cjs,.mjs",
|
|
49
|
+
"typecheck": "tsc --noEmit",
|
|
50
|
+
"format": "prettier --write .",
|
|
51
|
+
"format:check": "prettier --check ."
|
|
52
|
+
},
|
|
53
|
+
"peerDependencies": {
|
|
54
|
+
"@karni/ui": "^0.5.0",
|
|
55
|
+
"@tanstack/react-query": "^5.0.0",
|
|
56
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
57
|
+
"react-dom": "^18.0.0 || ^19.0.0"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@karni/ui": "file:../../../packages/karni-ui",
|
|
61
|
+
"@storybook/react": "^10.6.3",
|
|
62
|
+
"@tanstack/react-query": "^5.56.0",
|
|
63
|
+
"@testing-library/jest-dom": "^6.5.0",
|
|
64
|
+
"@testing-library/react": "^16.0.1",
|
|
65
|
+
"@testing-library/user-event": "^14.5.2",
|
|
66
|
+
"@types/node": "^24.0.0",
|
|
67
|
+
"@types/react": "^18.3.5",
|
|
68
|
+
"@types/react-dom": "^18.3.0",
|
|
69
|
+
"@typescript-eslint/eslint-plugin": "^8.71.2",
|
|
70
|
+
"@typescript-eslint/parser": "^8.71.2",
|
|
71
|
+
"@vitejs/plugin-react": "^6.1.2",
|
|
72
|
+
"eslint": "^8.57.0",
|
|
73
|
+
"eslint-config-prettier": "^9.1.0",
|
|
74
|
+
"eslint-plugin-react-hooks": "^4.6.2",
|
|
75
|
+
"jsdom": "^25.0.0",
|
|
76
|
+
"msw": "^2.4.4",
|
|
77
|
+
"prettier": "^3.3.3",
|
|
78
|
+
"react": "^18.3.1",
|
|
79
|
+
"react-dom": "^18.3.1",
|
|
80
|
+
"storybook": "^10.6.3",
|
|
81
|
+
"typescript": "^5.6.2",
|
|
82
|
+
"vite": "^8.3.4",
|
|
83
|
+
"vite-plugin-dts": "^5.1.2",
|
|
84
|
+
"vitest": "^5.0.5"
|
|
85
|
+
},
|
|
86
|
+
"publishConfig": {
|
|
87
|
+
"access": "public",
|
|
88
|
+
"provenance": true
|
|
89
|
+
},
|
|
90
|
+
"overrides": {
|
|
91
|
+
"minimatch@>=7.0.0 <11.0.1": "^11.0.5"
|
|
92
|
+
}
|
|
93
|
+
}
|