@struktur/http 2.6.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/AGENTS.md ADDED
@@ -0,0 +1,299 @@
1
+ # HTTP Package
2
+
3
+ HTTP API server for running Struktur headlessly.
4
+
5
+ ## Overview
6
+
7
+ This package provides a simple HTTP API for parsing files and extracting structured data using Struktur. It runs on Bun with Hono and `hono-openapi` for auto-generated OpenAPI documentation.
8
+
9
+ ## File Structure
10
+
11
+ ```
12
+ src/
13
+ index.ts # Bun.serve() bootstrap
14
+ app.ts # Hono app instance, middleware, route mounting
15
+ config.ts # Environment variable loading
16
+ schemas.ts # Zod schemas (Standard Schema compliant)
17
+ middleware/
18
+ auth.ts # Bearer token auth with /openapi.json whitelist
19
+ routes/
20
+ info.ts # GET /
21
+ parse.ts # POST /parse
22
+ extract.ts # POST /extract (SSE by default, JSON with `?sse=false`; dual-mode: JSON + multipart + form)
23
+ extract-stream.ts # POST /extract/stream (convenience alias, always SSE)
24
+ client.ts # GET /client (Scalar API client UI)
25
+ debug.ts # GET /debug (simple HTML upload/debug UI)
26
+ utils/
27
+ serialize.ts # Artifact serialization helpers
28
+ extraction.ts # Shared extraction primitives (parseExtractRequest, resolveModelForEnv, createStrategy)
29
+ ```
30
+
31
+ ## Quick Start
32
+
33
+ ```bash
34
+ # Start the server (port 3031 by default)
35
+ bun run start
36
+
37
+ # Or with hot reload for development
38
+ bun run dev
39
+
40
+ # With auth enabled
41
+ API_KEY=secret-key bun run start
42
+
43
+ # With a specific provider key
44
+ OPENAI_API_KEY=sk-... bun run start
45
+ ```
46
+
47
+ ## API Client UI
48
+
49
+ Open `http://localhost:3031/client` in your browser for an interactive Scalar API client. The documentation is also available at `http://localhost:3031/openapi.json`.
50
+
51
+ ## Endpoints
52
+
53
+ ### `GET /`
54
+
55
+ Returns API info and available endpoints.
56
+
57
+ ### `GET /client`
58
+
59
+ Interactive Scalar API client UI (auto-generated from the OpenAPI spec). No auth required.
60
+
61
+ ### `GET /debug`
62
+
63
+ Simple HTML debug page for uploading files and visualizing extraction output in real-time. Submits to `/extract/stream` and displays all SSE events plus the final pretty-printed JSON result. No auth required. Uses Tailwind CSS via CDN.
64
+
65
+ ### `GET /openapi.json`
66
+
67
+ OpenAPI 3.1.0 specification. No auth required.
68
+
69
+ ### `POST /parse`
70
+
71
+ Parse uploaded files into artifact JSON.
72
+
73
+ **Request:**
74
+ - Content-Type: `multipart/form-data`
75
+ - Fields:
76
+ - `file` (required): File to parse
77
+ - `images` (optional): Extract embedded images from documents (PDFs)
78
+ - `screenshots` (optional): Render page screenshots
79
+ - `screenshotScale` (optional): Scale factor for screenshots
80
+ - `screenshotWidth` (optional): Target width in pixels for screenshots
81
+
82
+ **Response:**
83
+ ```json
84
+ {
85
+ "artifacts": [...]
86
+ }
87
+ ```
88
+
89
+ ### `POST /extract`
90
+
91
+ Extract structured data from documents or artifact JSON.
92
+
93
+ **Streaming behavior:** By default, returns SSE (`text/event-stream`). Disable streaming with `?sse=false` to get a plain JSON response.
94
+
95
+ **Request (JSON):**
96
+ ```json
97
+ {
98
+ "artifacts": [...],
99
+ "schema": {...},
100
+ "model": "openai/gpt-4.1-mini",
101
+ "strategy": "simple",
102
+ "chunkSize": 10000,
103
+ "strict": false
104
+ }
105
+ ```
106
+
107
+ **Request (multipart/form-data):**
108
+ - `artifacts` (optional): Artifact JSON string
109
+ - `file` (optional): File to parse (alternative to artifacts)
110
+ - `schema` (optional): JSON schema string
111
+ - `fields` (optional): Shorthand field list (alternative to schema)
112
+ - `model` (required): Model identifier (e.g., `openai/gpt-4.1-mini`, `anthropic/claude-sonnet-4-6`)
113
+ - `strategy` (optional): Extraction strategy (default: `simple`)
114
+ - `chunkSize` (optional): Token budget per batch (default: 10000)
115
+ - `maxSteps` (optional): Maximum agent steps for agent strategy
116
+ - `strict` (optional): Strict schema validation
117
+ - `images` (optional): Extract embedded images (when using file)
118
+ - `screenshots` (optional): Render page screenshots (when using file)
119
+
120
+ **Request (application/x-www-form-urlencoded):**
121
+ Same fields as multipart, but `artifacts` and `schema` must be JSON strings. No file upload support.
122
+
123
+ **Response (default SSE):** `text/event-stream` — see event types below.
124
+
125
+ **Response (`?sse=false`):**
126
+ ```json
127
+ {
128
+ "data": {...},
129
+ "usage": {
130
+ "inputTokens": 100,
131
+ "outputTokens": 50,
132
+ "totalTokens": 150
133
+ }
134
+ }
135
+ ```
136
+
137
+ ### `POST /extract/stream`
138
+
139
+ Convenience alias that always streams via SSE. Accepts the same request formats as `POST /extract`.
140
+
141
+ **Response:** `text/event-stream`
142
+
143
+ Each event is a JSON object with a `type` field:
144
+
145
+ | Event type | Description |
146
+ |-----------|-------------|
147
+ | `step` | Extraction step started/completed |
148
+ | `progress` | Batch progress (current/total/percent) |
149
+ | `message` | LLM message sent/received |
150
+ | `tokenUsage` | Token usage update |
151
+ | `retry` | Retry attempt |
152
+ | `agent_tool_start` | Agent tool invocation started |
153
+ | `agent_tool_end` | Agent tool invocation completed |
154
+ | `agent_message` | Agent message |
155
+ | `agent_reasoning` | Agent reasoning/thought |
156
+ | `complete` | Final result with `data` and `usage` |
157
+ | `error` | Error message |
158
+
159
+ **Example (curl):**
160
+ ```bash
161
+ curl -N -X POST http://localhost:3031/extract \
162
+ -H "Content-Type: application/json" \
163
+ -d '{
164
+ "artifacts": [{"id":"1","type":"text","contents":[{"text":"test"}]}],
165
+ "schema": {"type":"object","properties":{"name":{"type":"string"}}},
166
+ "model": "openai/gpt-4o-mini"
167
+ }'
168
+ ```
169
+
170
+ Disable SSE to get plain JSON:
171
+ ```bash
172
+ curl -X POST "http://localhost:3031/extract?sse=false" \
173
+ -H "Content-Type: application/json" \
174
+ -d '{
175
+ "artifacts": [{"id":"1","type":"text","contents":[{"text":"test"}]}],
176
+ "schema": {"type":"object","properties":{"name":{"type":"string"}}},
177
+ "model": "openai/gpt-4o-mini"
178
+ }'
179
+ ```
180
+
181
+ ## Example Requests
182
+
183
+ ### Parse a file
184
+
185
+ ```bash
186
+ curl -X POST http://localhost:3031/parse \
187
+ -F "file=@document.pdf" \
188
+ -F "images=true"
189
+ ```
190
+
191
+ ### Extract with JSON body (pre-parsed artifacts)
192
+
193
+ ```bash
194
+ curl -X POST http://localhost:3031/extract \
195
+ -H "Content-Type: application/json" \
196
+ -d '{
197
+ "artifacts": [{"id":"1","type":"text","contents":[{"text":"John Doe works at Acme Corp"}]}],
198
+ "schema": {
199
+ "type": "object",
200
+ "properties": {
201
+ "name": {"type": "string"},
202
+ "company": {"type": "string"}
203
+ }
204
+ },
205
+ "model": "openai/gpt-4o-mini",
206
+ "strategy": "simple"
207
+ }'
208
+ ```
209
+
210
+ ### Extract with file upload (parse + extract in one call)
211
+
212
+ ```bash
213
+ curl -X POST http://localhost:3031/extract \
214
+ -F "file=@document.pdf" \
215
+ -F 'schema={"type":"object","properties":{"title":{"type":"string"}}}' \
216
+ -F "model=openai/gpt-4o-mini" \
217
+ -F "strategy=parallel" \
218
+ -F "chunkSize=5000"
219
+ ```
220
+
221
+ ### Stream extraction with SSE (default)
222
+
223
+ ```bash
224
+ curl -N -X POST http://localhost:3031/extract \
225
+ -H "Content-Type: application/json" \
226
+ -d '{
227
+ "artifacts": [{"id":"1","type":"text","contents":[{"text":"test"}]}],
228
+ "schema": {"type":"object","properties":{"name":{"type":"string"}}},
229
+ "model": "openai/gpt-4o-mini"
230
+ }'
231
+ ```
232
+
233
+ ### Extract with JSON response (disable SSE)
234
+
235
+ ```bash
236
+ curl -X POST "http://localhost:3031/extract?sse=false" \
237
+ -H "Content-Type: application/json" \
238
+ -d '{
239
+ "artifacts": [{"id":"1","type":"text","contents":[{"text":"test"}]}],
240
+ "schema": {"type":"object","properties":{"name":{"type":"string"}}},
241
+ "model": "openai/gpt-4o-mini"
242
+ }'
243
+ ```
244
+
245
+ ### With authentication enabled
246
+
247
+ ```bash
248
+ curl -X POST http://localhost:3031/extract \
249
+ -H "Authorization: Bearer secret-key" \
250
+ -H "Content-Type: application/json" \
251
+ -d '{"artifacts": [...], "schema": {...}, "model": "openai/gpt-4o-mini"}'
252
+ ```
253
+
254
+ ## Authentication
255
+
256
+ If `API_KEY` environment variable is set, all requests must include:
257
+ ```
258
+ Authorization: Bearer <api-key>
259
+ ```
260
+
261
+ ## Environment Variables
262
+
263
+ - `API_KEY`: API key for authentication (optional)
264
+ - `PORT`: Server port (default: 3031)
265
+ - `OPENAI_API_KEY`: OpenAI API key
266
+ - `ANTHROPIC_API_KEY`: Anthropic API key
267
+ - `GOOGLE_API_KEY`: Google API key
268
+ - `OPENCODE_API_KEY`: OpenCode API key
269
+ - `OPENROUTER_API_KEY`: OpenRouter API key
270
+
271
+ ## Development
272
+
273
+ ```bash
274
+ # Install dependencies
275
+ bun install
276
+
277
+ # Start development server with hot reload
278
+ bun run dev
279
+
280
+ # Start production server
281
+ bun run start
282
+
283
+ # Run tests
284
+ bun test
285
+ ```
286
+
287
+ ## Supported Strategies
288
+
289
+ - `simple`: Single-pass extraction
290
+ - `parallel`: Parallel batch processing with merge
291
+ - `sequential`: Sequential batch processing
292
+ - `parallelAutoMerge`: Parallel with auto-deduplication
293
+ - `sequentialAutoMerge`: Sequential with auto-deduplication
294
+ - `doublePass`: Two-pass extraction with merge
295
+ - `doublePassAutoMerge`: Two-pass with auto-deduplication
296
+ - `agent`: Agent-based extraction (requires `maxSteps`)
297
+ - Uses a sandboxed emulated shell with only read/grep/glob file utilities
298
+ - No external HTTP calls or command execution
299
+ - No custom VM needed - runs safely in the same process
package/LICENSE ADDED
@@ -0,0 +1,110 @@
1
+ # Functional Source License, Version 1.1, MIT Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 mateffy
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
100
+
101
+ The above copyright notice and this permission notice shall be included in all
102
+ copies or substantial portions of the Software.
103
+
104
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
105
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
106
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
107
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
108
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
109
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
110
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@struktur/http",
3
+ "version": "2.6.0",
4
+ "license": "FSL-1.1-MIT",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "dependencies": {
9
+ "@ai-sdk/anthropic": "^3.0.0",
10
+ "@ai-sdk/google": "^3.0.0",
11
+ "@ai-sdk/openai": "^3.0.0",
12
+ "@hono/node-server": "^2.0.0",
13
+ "@hono/standard-validator": "^0.2.2",
14
+ "@openrouter/ai-sdk-provider": "^2.0.0",
15
+ "@scalar/hono-api-reference": "^0.10.10",
16
+ "hono": "^4.6.0",
17
+ "hono-openapi": "^1.3.0",
18
+ "zod": "^4.3.6",
19
+ "@struktur/sdk": "2.6.0"
20
+ },
21
+ "devDependencies": {
22
+ "@types/bun": "latest",
23
+ "typescript": "^5"
24
+ },
25
+ "scripts": {
26
+ "dev": "bun --hot src/index.ts",
27
+ "start": "bun src/index.ts",
28
+ "test": "bun test"
29
+ }
30
+ }
package/src/app.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { Hono } from "hono";
2
+ import { cors } from "hono/cors";
3
+ import { openAPIRouteHandler } from "hono-openapi";
4
+ import { authMiddleware } from "./middleware/auth";
5
+ import infoApp from "./routes/info";
6
+ import parseApp from "./routes/parse";
7
+ import extractApp from "./routes/extract";
8
+ import extractStreamApp from "./routes/extract-stream";
9
+ import clientApp from "./routes/client";
10
+ import debugApp from "./routes/debug";
11
+ import packageJson from "../package.json" with { type: "json" };
12
+
13
+ const app = new Hono();
14
+
15
+ app.use("*", cors());
16
+ app.use("*", authMiddleware);
17
+
18
+ // Mount sub-routes
19
+ app.route("/", infoApp);
20
+ app.route("/", parseApp);
21
+ app.route("/", extractApp);
22
+ app.route("/", extractStreamApp);
23
+ app.route("/client", clientApp);
24
+ app.route("/debug", debugApp);
25
+
26
+ // OpenAPI documentation
27
+ app.get(
28
+ "/openapi.json",
29
+ openAPIRouteHandler(app, {
30
+ documentation: {
31
+ info: {
32
+ title: "Struktur HTTP API",
33
+ version: packageJson.version,
34
+ description:
35
+ "HTTP API for running Struktur headlessly. Parse files into artifacts and extract structured data using LLMs.",
36
+ },
37
+ servers: [
38
+ {
39
+ url: "http://localhost:3031",
40
+ description: "Local development server",
41
+ },
42
+ ],
43
+ tags: [
44
+ { name: "Info", description: "API information" },
45
+ { name: "Parse", description: "File parsing operations" },
46
+ { name: "Extract", description: "Data extraction operations" },
47
+ ],
48
+ },
49
+ }),
50
+ );
51
+
52
+ export { app };
package/src/config.ts ADDED
@@ -0,0 +1,9 @@
1
+ export const config = {
2
+ API_KEY: process.env.API_KEY || "",
3
+ PORT: parseInt(process.env.PORT || "3031"),
4
+ OPENAI_API_KEY: process.env.OPENAI_API_KEY,
5
+ ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
6
+ GOOGLE_API_KEY: process.env.GOOGLE_API_KEY,
7
+ OPENCODE_API_KEY: process.env.OPENCODE_API_KEY,
8
+ OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY,
9
+ } as const;