@howells/fieldwork-sdk 0.5.2 → 0.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/README.md +25 -24
- package/dist/{adapter-BhTK51Yj.d.ts → adapter-Bh8EIrNe.d.ts} +1 -1
- package/dist/brave.d.ts +1 -1
- package/dist/brave.js +3 -1
- package/dist/browserbase.d.ts +7 -2
- package/dist/browserbase.js +5 -3
- package/dist/{document-CjMeBtV5.js → document-Clmi51Sf.js} +4 -1
- package/dist/exa.d.ts +2 -2
- package/dist/exa.js +21 -12
- package/dist/{fieldwork-CseCD_-H.d.ts → fieldwork-BaWqUNI3.d.ts} +1 -1
- package/dist/firecrawl.d.ts +2 -2
- package/dist/firecrawl.js +76 -52
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/job-CWHOfhP_.js +102 -0
- package/dist/kernel.d.ts +99 -0
- package/dist/kernel.js +313 -0
- package/dist/llamaparse.d.ts +1 -1
- package/dist/llamaparse.js +18 -11
- package/dist/parallel.d.ts +8 -4
- package/dist/parallel.js +72 -27
- package/dist/{parse-BY3R0oWO.js → parse-COHKvfH9.js} +61 -8
- package/dist/perplexity.d.ts +2 -2
- package/dist/perplexity.js +58 -38
- package/dist/reducto.d.ts +1 -1
- package/dist/reducto.js +18 -11
- package/dist/{schema-CNd51xdD.d.ts → schema-BWWiMvkg.d.ts} +1 -1
- package/dist/serpapi.d.ts +1 -1
- package/dist/serpapi.js +1 -1
- package/dist/tavily.d.ts +2 -2
- package/dist/tavily.js +18 -11
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +22 -3
- package/package.json +9 -2
- package/dist/job-DVsmQMKP.js +0 -47
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Fieldwork
|
|
2
2
|
|
|
3
|
-
One API for searching the web, reading pages, extracting values, walking sites, answering and researching questions, finding entities, watching for changes, driving a browser and parsing documents, across Exa, Firecrawl, Tavily, Parallel, Perplexity, Brave, SerpApi, Browserbase, LlamaParse and Reducto.
|
|
3
|
+
One API for searching the web, reading pages, extracting values, walking sites, answering and researching questions, finding entities, watching for changes, driving a browser and parsing documents, across Exa, Firecrawl, Tavily, Parallel, Perplexity, Brave, SerpApi, Browserbase, Kernel, LlamaParse and Reducto.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
npm i @howells/fieldwork-sdk
|
|
@@ -24,25 +24,25 @@ Swap the adapter to switch providers. Everything below the constructor stays the
|
|
|
24
24
|
|
|
25
25
|
Each instance has only the methods its provider offers, so a call the provider cannot serve does not compile. `new Fieldwork({ adapter: tavily() }).act(...)` is a type error, because Tavily has no browser. Untyped JavaScript gets a `FieldworkError` with code `Unsupported`, and no request is sent. Nothing falls back to another provider, and nothing is emulated: a provider without an answer endpoint has no `answer`, even though search plus a model could imitate one.
|
|
26
26
|
|
|
27
|
-
| Method | Exa | Firecrawl | Tavily | Parallel | Perplexity | Brave | SerpApi | Browserbase | LlamaParse | Reducto |
|
|
28
|
-
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
29
|
-
| `search(query)` | yes | yes | yes | yes | yes | yes | yes | yes | | |
|
|
30
|
-
| `images(query)` | | yes | yes | yes | | yes | yes | | | |
|
|
31
|
-
| `read(url)` | yes | yes | yes | yes | | | | yes | | |
|
|
32
|
-
| `readMany(urls)` | yes | yes | yes | yes | | | | | | |
|
|
33
|
-
| `extract(url, { schema })` | yes | yes | | yes | | | | | | |
|
|
34
|
-
| `product(url)` | | yes | | | | | | | | |
|
|
35
|
-
| `map(url)` | | yes | yes | | | | | | | |
|
|
36
|
-
| `crawl(url)` | | yes | yes | | | | | | | |
|
|
37
|
-
| `answer(question)` | yes | | yes | yes | yes | yes | | | | |
|
|
38
|
-
| `research(question)` | yes | yes | yes | yes | yes | | | | | |
|
|
39
|
-
| `discover(objective, { entityType, conditions })` | | | | yes | | | | | | |
|
|
40
|
-
| `decide(context, questions)` | | | | yes | yes | | | | | |
|
|
41
|
-
| `act(code)` | | yes | | | | | | | | |
|
|
42
|
-
| `browser.open()`, `browser.close(id)` | | yes | | | | | | yes | | |
|
|
43
|
-
| `parse(document)` | | yes | | | | | | | yes | yes |
|
|
44
|
-
| `monitor.create()`, `.get`, `.list`, `.delete`, `.events` | yes | yes | | yes | | | | | | |
|
|
45
|
-
| `usage()` | | yes | yes | | | | yes | yes | | |
|
|
27
|
+
| Method | Exa | Firecrawl | Tavily | Parallel | Perplexity | Brave | SerpApi | Browserbase | Kernel | LlamaParse | Reducto |
|
|
28
|
+
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
29
|
+
| `search(query)` | yes | yes | yes | yes | yes | yes | yes | yes | | | |
|
|
30
|
+
| `images(query)` | | yes | yes | yes | | yes | yes | | | | |
|
|
31
|
+
| `read(url)` | yes | yes | yes | yes | | | | yes | yes | | |
|
|
32
|
+
| `readMany(urls)` | yes | yes | yes | yes | | | | | | | |
|
|
33
|
+
| `extract(url, { schema })` | yes | yes | | yes | | | | | | | |
|
|
34
|
+
| `product(url)` | | yes | | | | | | | | | |
|
|
35
|
+
| `map(url)` | | yes | yes | | | | | | | | |
|
|
36
|
+
| `crawl(url)` | | yes | yes | | | | | | | | |
|
|
37
|
+
| `answer(question)` | yes | | yes | yes | yes | yes | | | | | |
|
|
38
|
+
| `research(question)` | yes | yes | yes | yes | yes | | | | | | |
|
|
39
|
+
| `discover(objective, { entityType, conditions })` | | | | yes | | | | | | | |
|
|
40
|
+
| `decide(context, questions)` | | | | yes | yes | | | | | | |
|
|
41
|
+
| `act(code)` | | yes | | | | | | | | | |
|
|
42
|
+
| `browser.open()`, `browser.close(id)` | | yes | | | | | | yes | yes | | |
|
|
43
|
+
| `parse(document)` | | yes | | | | | | | | yes | yes |
|
|
44
|
+
| `monitor.create()`, `.get`, `.list`, `.delete`, `.events` | yes | yes | | yes | | | | | | | |
|
|
45
|
+
| `usage()` | | yes | yes | | | | yes | yes | | | |
|
|
46
46
|
|
|
47
47
|
`web.capabilities` and `web.supports("crawl")` report the same table at runtime.
|
|
48
48
|
|
|
@@ -110,7 +110,7 @@ A job that stopped early but produced output, for example on a credit or step li
|
|
|
110
110
|
|
|
111
111
|
### Long jobs
|
|
112
112
|
|
|
113
|
-
Research, discovery, crawls, batch reads, Parallel extraction and LlamaParse and Reducto parses are polled until they finish. Pass `timeout` and `signal` to bound or cancel any call.
|
|
113
|
+
Research, discovery, crawls, batch reads, Parallel extraction and LlamaParse and Reducto parses are polled until they finish. A job status the provider does not document throws `ProviderError` with `jobId` at once, instead of polling until the timeout. Pass `timeout` and `signal` to bound or cancel any call.
|
|
114
114
|
|
|
115
115
|
When a job outlasts `timeout`, or `signal` stops the wait, the provider keeps running it and charging for it. The error carries the job's id as `jobId`; pass it back as `resume` to collect the result instead of starting another job:
|
|
116
116
|
|
|
@@ -191,11 +191,11 @@ Every failure is a `FieldworkError`. It carries:
|
|
|
191
191
|
| `NotFound` | The page, product or job does not exist. | Check the URL or id. |
|
|
192
192
|
| `InvalidRequest` | The input was refused, by Fieldwork or by the provider. | Correct the input; the message says what is wrong. |
|
|
193
193
|
| `JobFailed` | The job ended without a result. | Start a new job if needed; resuming fails again. |
|
|
194
|
-
| `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat. |
|
|
194
|
+
| `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat when `retryable` is true. |
|
|
195
195
|
| `Aborted` | `signal` cancelled the call. | With `jobId`, the job may still be running; pass it as `resume`. |
|
|
196
196
|
| `ProviderError` | Any other provider failure. | Repeat when `retryable` is true (5xx and network failures). |
|
|
197
197
|
|
|
198
|
-
An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job.
|
|
198
|
+
An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job. Nor is a failure, other than a rate limit, of the request that starts a job, session or monitor: the provider may already have started it, so check before repeating.
|
|
199
199
|
|
|
200
200
|
### Retries
|
|
201
201
|
|
|
@@ -265,9 +265,10 @@ On a router, `raw` is keyed by provider name.
|
|
|
265
265
|
| `brave()` | `BRAVE_API_KEY` |
|
|
266
266
|
| `serpapi()` | `SERPAPI_API_KEY` |
|
|
267
267
|
| `browserbase()` | `BROWSERBASE_API_KEY` |
|
|
268
|
+
| `kernel()` | `KERNEL_API_KEY` |
|
|
268
269
|
| `llamaparse()` | `LLAMA_CLOUD_API_KEY` |
|
|
269
270
|
| `reducto()` | `REDUCTO_API_KEY` |
|
|
270
271
|
|
|
271
272
|
Pass `apiKey` (and Browserbase's `projectId`) to override, and `fetch` to supply your own. Requests follow redirects only within the provider's origin; a redirect to any other host, scheme or port fails before the key is sent there.
|
|
272
273
|
|
|
273
|
-
ESM only, Node 22 or later. The
|
|
274
|
+
ESM only, Node 22 or later. The dependencies are Zod and, for Kernel's Markdown, Turndown.
|
|
@@ -518,7 +518,7 @@ interface RequestOptions extends CallOptions {
|
|
|
518
518
|
* The request creates a job, session or monitor that the provider bills for
|
|
519
519
|
* or keeps. After a 5xx or a dropped connection the provider may already
|
|
520
520
|
* have created it, so only a rate limit, which it has certainly not acted
|
|
521
|
-
* on, is retried
|
|
521
|
+
* on, is retried, and any other failure is thrown not `retryable`.
|
|
522
522
|
*/
|
|
523
523
|
creates?: boolean;
|
|
524
524
|
/** The endpoint answers in text, such as an event stream, so its body is returned as a string. */
|
package/dist/brave.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, t as Adapter } from "./adapter-
|
|
1
|
+
import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, t as Adapter } from "./adapter-Bh8EIrNe.js";
|
|
2
2
|
/** Settings for `brave()`. */
|
|
3
3
|
interface BraveConfig {
|
|
4
4
|
/** Defaults to the BRAVE_API_KEY environment variable. */
|
package/dist/brave.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
2
|
import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
3
|
-
import { C as createRawClient, F as parseJson, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf, z as refuseTogether } from "./parse-
|
|
3
|
+
import { C as createRawClient, F as parseJson, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf, z as refuseTogether } from "./parse-COHKvfH9.js";
|
|
4
4
|
import * as z from "zod/mini";
|
|
5
5
|
// src/adapters/brave/response.ts
|
|
6
6
|
/** The `query` block every search response carries. */
|
|
@@ -140,6 +140,7 @@ const ALLOWED = {
|
|
|
140
140
|
news: [
|
|
141
141
|
...SHARED,
|
|
142
142
|
"vertical",
|
|
143
|
+
"content",
|
|
143
144
|
"offset",
|
|
144
145
|
"extraSnippets",
|
|
145
146
|
"spellcheck",
|
|
@@ -150,6 +151,7 @@ const ALLOWED = {
|
|
|
150
151
|
videos: [
|
|
151
152
|
...SHARED,
|
|
152
153
|
"vertical",
|
|
154
|
+
"content",
|
|
153
155
|
"offset",
|
|
154
156
|
"spellcheck",
|
|
155
157
|
"uiLanguage",
|
package/dist/browserbase.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as Page, Y as SearchResponse, a as RawClient, d as BrowserSession, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-
|
|
1
|
+
import { R as Page, Y as SearchResponse, a as RawClient, d as BrowserSession, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Bh8EIrNe.js";
|
|
2
2
|
/** Settings for `browserbase()`. */
|
|
3
3
|
export interface BrowserbaseConfig {
|
|
4
4
|
/** Defaults to the BROWSERBASE_API_KEY environment variable. */
|
|
@@ -34,7 +34,12 @@ export interface BrowserbaseReadOptions extends CallOptions {
|
|
|
34
34
|
* content stays in `raw`, with a warning.
|
|
35
35
|
*/
|
|
36
36
|
format?: "markdown" | "raw";
|
|
37
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* Follow HTTP redirects. Browserbase defaults to false, which returns the
|
|
39
|
+
* 3xx response itself; Fieldwork defaults to true so a read of an http, www
|
|
40
|
+
* or trailing-slash URL returns the page. `false` returns the redirect
|
|
41
|
+
* response, with a warning.
|
|
42
|
+
*/
|
|
38
43
|
allowRedirects?: boolean;
|
|
39
44
|
/** Skip TLS certificate verification, for self-signed or expired certificates. */
|
|
40
45
|
allowInsecureSsl?: boolean;
|
package/dist/browserbase.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
2
|
import { r as invalidRequest } from "./errors-DROZyb9T.js";
|
|
3
|
-
import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, r as arrayOf, s as optionalAnyString, z as refuseTogether } from "./parse-
|
|
3
|
+
import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, r as arrayOf, s as optionalAnyString, z as refuseTogether } from "./parse-COHKvfH9.js";
|
|
4
4
|
import * as z from "zod/mini";
|
|
5
5
|
// src/adapters/browserbase/response.ts
|
|
6
6
|
/** `POST /v1/sessions`. The id keeps the value as it arrived, for the error raised when there is none. */
|
|
@@ -146,7 +146,7 @@ const browserbase = (config = {}) => {
|
|
|
146
146
|
...call,
|
|
147
147
|
body: compact({
|
|
148
148
|
allowInsecureSsl: o.allowInsecureSsl,
|
|
149
|
-
allowRedirects: o.allowRedirects,
|
|
149
|
+
allowRedirects: o.allowRedirects ?? true,
|
|
150
150
|
contextId: o.contextId,
|
|
151
151
|
format,
|
|
152
152
|
proxies: fetchProxies(o),
|
|
@@ -157,11 +157,13 @@ const browserbase = (config = {}) => {
|
|
|
157
157
|
const { content } = body;
|
|
158
158
|
const binary = body.encoding === "base64";
|
|
159
159
|
const contentType = body.contentType ?? "";
|
|
160
|
+
const redirected = o.allowRedirects === false && body.statusCode !== void 0 && body.statusCode >= 300 && body.statusCode < 400;
|
|
161
|
+
const warnings = [...binary ? ["the response is binary; its Base64 content is in raw"] : [], ...redirected ? [`the page answered with a ${body.statusCode} redirect and allowRedirects is false, so nothing was followed`] : []];
|
|
160
162
|
return presentPage(provider, compact({
|
|
161
163
|
markdown: format === "markdown" && !binary ? content : void 0,
|
|
162
164
|
meta: meta({
|
|
163
165
|
requestId: body.id,
|
|
164
|
-
warnings:
|
|
166
|
+
warnings: warnings.length > 0 ? warnings : void 0
|
|
165
167
|
}),
|
|
166
168
|
raw: response,
|
|
167
169
|
rawHtml: format === "raw" && !binary && contentType.includes("html") ? content : void 0,
|
|
@@ -30,9 +30,12 @@ const refuseLarger = (provider, document, maxMegabytes) => {
|
|
|
30
30
|
const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
|
|
31
31
|
if (size > maxMegabytes * 1024 * 1024) throw new FieldworkError("InvalidRequest", `${provider} parses files up to ${maxMegabytes} MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`, { provider });
|
|
32
32
|
};
|
|
33
|
+
/** Whether the bytes sit on an ArrayBuffer rather than a SharedArrayBuffer. */
|
|
34
|
+
const onArrayBuffer = (bytes) => bytes.buffer instanceof ArrayBuffer;
|
|
33
35
|
/** The file's bytes as a multipart part, with the content type its extension names. */
|
|
34
36
|
const documentPart = (document) => {
|
|
35
|
-
const
|
|
37
|
+
const { data } = document;
|
|
38
|
+
const part = data instanceof Uint8Array && !onArrayBuffer(data) ? new Uint8Array(data) : data;
|
|
36
39
|
return new Blob([part], { type: mediaTypeOf(document.name) ?? "application/octet-stream" });
|
|
37
40
|
};
|
|
38
41
|
/** The smallest box that holds every one of `boxes`, or undefined when there are none. */
|
package/dist/exa.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, l as Answer, p as CallOptions, q as Research, t as Adapter, z as PageBatch } from "./adapter-
|
|
2
|
-
import { t as OutputSchema } from "./schema-
|
|
1
|
+
import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, l as Answer, p as CallOptions, q as Research, t as Adapter, z as PageBatch } from "./adapter-Bh8EIrNe.js";
|
|
2
|
+
import { t as OutputSchema } from "./schema-BWWiMvkg.js";
|
|
3
3
|
/** Settings for the Exa adapter. */
|
|
4
4
|
interface ExaConfig {
|
|
5
5
|
/** Defaults to the EXA_API_KEY environment variable. */
|
package/dist/exa.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
2
|
import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
3
|
-
import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, N as hours, P as meta, R as record, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-
|
|
4
|
-
import {
|
|
3
|
+
import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, N as hours, P as meta, R as record, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-COHKvfH9.js";
|
|
4
|
+
import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
|
|
5
5
|
import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
|
|
6
6
|
import * as z from "zod/mini";
|
|
7
7
|
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
|
|
@@ -187,9 +187,20 @@ const researchBody = (question, o) => {
|
|
|
187
187
|
systemPrompt: o.systemPrompt
|
|
188
188
|
});
|
|
189
189
|
};
|
|
190
|
+
const RUN_STATES = {
|
|
191
|
+
done: ["completed"],
|
|
192
|
+
failed: ["failed", "cancelled"],
|
|
193
|
+
running: ["queued", "running"]
|
|
194
|
+
};
|
|
195
|
+
/** The run once it has stopped, undefined while it runs. A failed or cancelled run can still carry partial output, so `researchResult` decides what it amounts to. */
|
|
196
|
+
const runState = (id, entry) => jobState("exa", id, RUN_STATES, {
|
|
197
|
+
original: entry.original,
|
|
198
|
+
value: entry.value.status
|
|
199
|
+
}) === "running" ? void 0 : entry;
|
|
190
200
|
/**
|
|
191
201
|
* The result of a finished run. A run that did not complete and has no output
|
|
192
|
-
* throws `JobFailed` with Exa's error
|
|
202
|
+
* throws `JobFailed` with Exa's error, and so does a completed run without
|
|
203
|
+
* it. Otherwise the result is `completed`
|
|
193
204
|
* only when the run completed and stopped for no reason or with
|
|
194
205
|
* `schema_satisfied`; any other finish is `partial`, with the stop reason.
|
|
195
206
|
* `continuationId` is the run's id once it has completed.
|
|
@@ -218,7 +229,10 @@ const researchResult = (id, entry, structured) => {
|
|
|
218
229
|
fields: fields.length > 0 ? fields : void 0,
|
|
219
230
|
id,
|
|
220
231
|
meta: runMeta(run),
|
|
221
|
-
output:
|
|
232
|
+
output: requireOutput("exa", id, {
|
|
233
|
+
original: entry.original,
|
|
234
|
+
value: structured ? output.structured : output.text
|
|
235
|
+
}),
|
|
222
236
|
raw: entry.original,
|
|
223
237
|
sources: uniqueCitations(fields.flatMap((field) => field.citations)),
|
|
224
238
|
status: finished ? "completed" : "partial",
|
|
@@ -616,11 +630,7 @@ const exa = (config = {}) => {
|
|
|
616
630
|
const { call, rest: o } = callSettings(options);
|
|
617
631
|
checkResearch(o);
|
|
618
632
|
return await runJob("exa", {
|
|
619
|
-
check: async (id, request) => {
|
|
620
|
-
const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request));
|
|
621
|
-
const { status } = current.value;
|
|
622
|
-
return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
|
|
623
|
-
},
|
|
633
|
+
check: async (id, request) => runState(id, z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request))),
|
|
624
634
|
finish: async (run, id) => {
|
|
625
635
|
const { outputSchema } = run.value.request;
|
|
626
636
|
const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
|
|
@@ -630,11 +640,10 @@ const exa = (config = {}) => {
|
|
|
630
640
|
output: await checkOutput(o.schema, result.output, { provider: "exa" })
|
|
631
641
|
};
|
|
632
642
|
},
|
|
633
|
-
start: async () =>
|
|
634
|
-
creates: true,
|
|
643
|
+
start: async () => await startJob(raw, "/agent/runs", {
|
|
635
644
|
...call,
|
|
636
645
|
body: researchBody(question, o)
|
|
637
|
-
})
|
|
646
|
+
}, RunStart, (reply) => reply.id)
|
|
638
647
|
}, {
|
|
639
648
|
...call,
|
|
640
649
|
interval: o.interval,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { m as Capability, n as AnyAdapter } from "./adapter-
|
|
1
|
+
import { m as Capability, n as AnyAdapter } from "./adapter-Bh8EIrNe.js";
|
|
2
2
|
/** Why a call failed. Branch on this, not on the message, which can change. */
|
|
3
3
|
type FieldworkErrorCode =
|
|
4
4
|
/** The adapter's provider does not offer this capability. */
|
package/dist/firecrawl.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as ParsedDocument, C as DocumentInput, E as Extraction, F as MonitorEvents, I as MonitorInfo, K as Recency, L as MonitorSchedule, Q as SiteMap, R as Page, U as Product, Y as SearchResponse, _ as Crawl, a as RawClient, c as ActResult, d as BrowserSession, j as ImageSearch, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-
|
|
2
|
-
import { t as OutputSchema } from "./schema-
|
|
1
|
+
import { B as ParsedDocument, C as DocumentInput, E as Extraction, F as MonitorEvents, I as MonitorInfo, K as Recency, L as MonitorSchedule, Q as SiteMap, R as Page, U as Product, Y as SearchResponse, _ as Crawl, a as RawClient, c as ActResult, d as BrowserSession, j as ImageSearch, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-Bh8EIrNe.js";
|
|
2
|
+
import { t as OutputSchema } from "./schema-BWWiMvkg.js";
|
|
3
3
|
/** Settings for the Firecrawl adapter. */
|
|
4
4
|
interface FirecrawlConfig {
|
|
5
5
|
/** Defaults to the FIRECRAWL_API_KEY environment variable. */
|
package/dist/firecrawl.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
2
|
import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
3
|
-
import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-
|
|
4
|
-
import {
|
|
3
|
+
import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-COHKvfH9.js";
|
|
4
|
+
import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
|
|
5
5
|
import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
|
|
6
|
-
import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-
|
|
6
|
+
import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-Clmi51Sf.js";
|
|
7
7
|
import * as z from "zod/mini";
|
|
8
8
|
// src/adapters/firecrawl/shared.ts
|
|
9
9
|
const provider = "firecrawl";
|
|
@@ -511,6 +511,31 @@ const failedPages = (errors) => errors.value.errors.map((entry) => ({
|
|
|
511
511
|
error: entry.error ?? "unknown error",
|
|
512
512
|
url: entry.url ?? ""
|
|
513
513
|
}));
|
|
514
|
+
const BATCH_STATES = {
|
|
515
|
+
done: ["completed"],
|
|
516
|
+
failed: ["failed", "cancelled"],
|
|
517
|
+
missingIsRunning: true,
|
|
518
|
+
running: ["scraping"]
|
|
519
|
+
};
|
|
520
|
+
const AGENT_STATES = {
|
|
521
|
+
done: ["completed"],
|
|
522
|
+
failed: ["failed", "cancelled"],
|
|
523
|
+
missingIsRunning: true,
|
|
524
|
+
running: ["processing"]
|
|
525
|
+
};
|
|
526
|
+
/** A crawl or batch scrape when it has finished, undefined while it runs; throws `JobFailed` when it failed or was cancelled. */
|
|
527
|
+
const batchState = (kind, id, entry) => {
|
|
528
|
+
const { status } = entry.value;
|
|
529
|
+
const state = jobState(provider, id, BATCH_STATES, {
|
|
530
|
+
original: entry.original,
|
|
531
|
+
value: status
|
|
532
|
+
});
|
|
533
|
+
if (state === "failed") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${status}`, {
|
|
534
|
+
cause: entry.original,
|
|
535
|
+
provider
|
|
536
|
+
});
|
|
537
|
+
return state === "done" ? entry : void 0;
|
|
538
|
+
};
|
|
514
539
|
/**
|
|
515
540
|
* The run when it has finished, undefined while it runs. A `failed` run that
|
|
516
541
|
* left partial output counts as finished; any other `failed` or `cancelled`
|
|
@@ -518,20 +543,22 @@ const failedPages = (errors) => errors.value.errors.map((entry) => ({
|
|
|
518
543
|
*/
|
|
519
544
|
const researchState = (id, entry) => {
|
|
520
545
|
const status = entry.value;
|
|
521
|
-
const state =
|
|
546
|
+
const state = jobState(provider, id, AGENT_STATES, {
|
|
547
|
+
original: entry.original,
|
|
548
|
+
value: status.status
|
|
549
|
+
});
|
|
522
550
|
const hasPartial = status.partial !== void 0 && status.partial !== null;
|
|
523
|
-
|
|
524
|
-
if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
|
|
551
|
+
if (state === "failed" && !(status.status === "failed" && hasPartial)) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${status.status}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
|
|
525
552
|
cause: entry.original,
|
|
526
553
|
provider
|
|
527
554
|
});
|
|
528
|
-
return
|
|
555
|
+
return state === "running" ? void 0 : entry;
|
|
529
556
|
};
|
|
530
557
|
/**
|
|
531
558
|
* The result of a finished run. A `failed` run with partial output is
|
|
532
559
|
* `partial`, with that output and a `stopReason`; any other is `completed`
|
|
533
|
-
* with `data`, else the message
|
|
534
|
-
* id is the run's thread.
|
|
560
|
+
* with `data`, else the message, and throws `JobFailed` when it has neither.
|
|
561
|
+
* `sources` is always empty. The continuation id is the run's thread.
|
|
535
562
|
*/
|
|
536
563
|
const researchResult = (id, started, entry) => {
|
|
537
564
|
const run = entry.value;
|
|
@@ -545,7 +572,10 @@ const researchResult = (id, started, entry) => {
|
|
|
545
572
|
requestId: id,
|
|
546
573
|
warnings: stopped ? [run.message.note, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0].filter((note) => note !== void 0) : void 0
|
|
547
574
|
}),
|
|
548
|
-
output: stopped ? run.partial :
|
|
575
|
+
output: stopped ? run.partial : requireOutput(provider, id, {
|
|
576
|
+
original: entry.original,
|
|
577
|
+
value: run.data ?? run.message.value
|
|
578
|
+
}),
|
|
549
579
|
raw: entry.original,
|
|
550
580
|
sources: [],
|
|
551
581
|
status,
|
|
@@ -1001,26 +1031,18 @@ const firecrawl = (config = {}) => {
|
|
|
1001
1031
|
response
|
|
1002
1032
|
};
|
|
1003
1033
|
};
|
|
1004
|
-
/** The path of a `next` link, relative to the base URL, so the next page of results goes through the same client. */
|
|
1034
|
+
/** The path of a `next` link, absolute or relative to the base URL, so the next page of results goes through the same client. */
|
|
1005
1035
|
const pathOf = (link) => {
|
|
1006
|
-
const
|
|
1007
|
-
const
|
|
1008
|
-
return next.pathname.slice(base.length) + next.search;
|
|
1036
|
+
const base = new URL(`${baseUrl.replace(/\/$/u, "")}/`);
|
|
1037
|
+
const next = new URL(link, base);
|
|
1038
|
+
return next.pathname.slice(base.pathname.length - 1) + next.search;
|
|
1009
1039
|
};
|
|
1010
1040
|
/**
|
|
1011
1041
|
* Runs a crawl or batch scrape: waits for it, then reads every page of its
|
|
1012
1042
|
* results and the pages that failed.
|
|
1013
1043
|
*/
|
|
1014
1044
|
const batchJob = async (kind, start, settings, finish) => await runJob(provider, {
|
|
1015
|
-
check: async (id, request) => {
|
|
1016
|
-
const status = z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request));
|
|
1017
|
-
const state = status.value.status;
|
|
1018
|
-
if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
|
|
1019
|
-
cause: status.original,
|
|
1020
|
-
provider
|
|
1021
|
-
});
|
|
1022
|
-
return state === "completed" ? status : void 0;
|
|
1023
|
-
},
|
|
1045
|
+
check: async (id, request) => batchState(kind, id, z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request))),
|
|
1024
1046
|
finish: async (first, id) => {
|
|
1025
1047
|
const path = `/${kind}/${segment(id)}`;
|
|
1026
1048
|
const request = {
|
|
@@ -1120,27 +1142,27 @@ const firecrawl = (config = {}) => {
|
|
|
1120
1142
|
},
|
|
1121
1143
|
async crawl(url, options) {
|
|
1122
1144
|
const { call, rest: o } = callSettings(options);
|
|
1123
|
-
return await batchJob("crawl", async () =>
|
|
1124
|
-
creates: true,
|
|
1145
|
+
return await batchJob("crawl", async () => await startJob(raw, "/crawl", {
|
|
1125
1146
|
...call,
|
|
1126
1147
|
body: crawlBody(url, o)
|
|
1127
|
-
})
|
|
1148
|
+
}, CrawlStart, (reply) => reply.id), {
|
|
1128
1149
|
...call,
|
|
1129
1150
|
interval: o.interval,
|
|
1130
1151
|
resume: o.resume
|
|
1131
1152
|
}, (job, id) => {
|
|
1132
1153
|
const { robotsBlocked } = job.errors.value;
|
|
1154
|
+
const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
|
|
1155
|
+
...toPage(item.value, url),
|
|
1156
|
+
raw: item.original
|
|
1157
|
+
}))));
|
|
1133
1158
|
return compact({
|
|
1134
|
-
failed: job.failed,
|
|
1159
|
+
failed: [...job.failed, ...gone],
|
|
1135
1160
|
id,
|
|
1136
1161
|
meta: meta({
|
|
1137
1162
|
credits: job.first.value.creditsUsed,
|
|
1138
1163
|
requestId: id
|
|
1139
1164
|
}),
|
|
1140
|
-
pages
|
|
1141
|
-
...toPage(item.value, url),
|
|
1142
|
-
raw: item.original
|
|
1143
|
-
}))),
|
|
1165
|
+
pages,
|
|
1144
1166
|
raw: {
|
|
1145
1167
|
batches: job.batches.map((batch) => batch.original),
|
|
1146
1168
|
errors: job.errors.original
|
|
@@ -1158,6 +1180,10 @@ const firecrawl = (config = {}) => {
|
|
|
1158
1180
|
schema: jsonSchemaOf(schema),
|
|
1159
1181
|
type: "json"
|
|
1160
1182
|
})], page, call);
|
|
1183
|
+
presentPage(provider, {
|
|
1184
|
+
...toPage(data, url),
|
|
1185
|
+
raw: response
|
|
1186
|
+
});
|
|
1161
1187
|
if (data.json === void 0) {
|
|
1162
1188
|
const why = data.warning.text;
|
|
1163
1189
|
throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
|
|
@@ -1285,19 +1311,18 @@ const firecrawl = (config = {}) => {
|
|
|
1285
1311
|
const { call, rest: o } = callSettings(options);
|
|
1286
1312
|
const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
|
|
1287
1313
|
let started = z.parse(RunStart, {});
|
|
1288
|
-
return await batchJob("batch/scrape", async () => {
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
}, {
|
|
1314
|
+
return await batchJob("batch/scrape", async () => await startJob(raw, "/batch/scrape", {
|
|
1315
|
+
...call,
|
|
1316
|
+
body: compact({
|
|
1317
|
+
urls,
|
|
1318
|
+
...readBody(read),
|
|
1319
|
+
maxConcurrency,
|
|
1320
|
+
ignoreInvalidURLs
|
|
1321
|
+
})
|
|
1322
|
+
}, RunStart, (reply) => {
|
|
1323
|
+
started = reply;
|
|
1324
|
+
return reply.value.id;
|
|
1325
|
+
}), {
|
|
1301
1326
|
...call,
|
|
1302
1327
|
interval,
|
|
1303
1328
|
resume
|
|
@@ -1342,14 +1367,13 @@ const firecrawl = (config = {}) => {
|
|
|
1342
1367
|
output: await checkOutput(o.schema, result.output, { provider })
|
|
1343
1368
|
};
|
|
1344
1369
|
},
|
|
1345
|
-
start: async () => {
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
}
|
|
1370
|
+
start: async () => await startJob(raw, "/agent", {
|
|
1371
|
+
...call,
|
|
1372
|
+
body: researchBody(question, o)
|
|
1373
|
+
}, RunStart, (reply) => {
|
|
1374
|
+
started = reply;
|
|
1375
|
+
return reply.value.id;
|
|
1376
|
+
})
|
|
1353
1377
|
}, {
|
|
1354
1378
|
...call,
|
|
1355
1379
|
interval: o.interval,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-
|
|
2
|
-
import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-
|
|
3
|
-
import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-
|
|
1
|
+
import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-Bh8EIrNe.js";
|
|
2
|
+
import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-BaWqUNI3.js";
|
|
3
|
+
import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-BWWiMvkg.js";
|
|
4
4
|
/** Which adapter serves each capability, for `router`. */
|
|
5
5
|
type Routes = Partial<Record<Capability, AnyAdapter>>;
|
|
6
6
|
/** Each route must name an adapter whose provider offers that capability. */
|
package/dist/index.js
CHANGED
|
@@ -23,7 +23,7 @@ const unsupported = (provider, capability) => {
|
|
|
23
23
|
throw new FieldworkError("Unsupported", `${provider} does not offer ${capability}`, { provider });
|
|
24
24
|
};
|
|
25
25
|
if (!GROUP_CAPABILITIES.includes(capability)) return refuse;
|
|
26
|
-
return new Proxy({}, { get: () => refuse });
|
|
26
|
+
return new Proxy({}, { get: (_target, key) => typeof key === "symbol" || key === "then" ? void 0 : refuse });
|
|
27
27
|
};
|
|
28
28
|
/**
|
|
29
29
|
* The implementation behind `Fieldwork`, typed loosely: each capability name
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { i as withJob, t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
2
|
+
import { B as requireJobId, D as sleep, O as stopped } from "./parse-COHKvfH9.js";
|
|
3
|
+
import * as z from "zod/mini";
|
|
4
|
+
// src/job.ts
|
|
5
|
+
/**
|
|
6
|
+
* Checks the job every `interval` until it has a finished state. Throws
|
|
7
|
+
* `Timeout` when another interval would pass the deadline, and `Aborted` or
|
|
8
|
+
* `Timeout` (by how the signal stopped) once the signal is aborted. Both carry
|
|
9
|
+
* `jobId`, because the job may still be running.
|
|
10
|
+
*/
|
|
11
|
+
const waitFor = async (provider, id, check, settings) => {
|
|
12
|
+
const interval = settings.interval ?? 2e3;
|
|
13
|
+
const deadline = Date.now() + (settings.timeout ?? 6e5);
|
|
14
|
+
const request = {
|
|
15
|
+
retries: settings.retries,
|
|
16
|
+
signal: settings.signal
|
|
17
|
+
};
|
|
18
|
+
for (;;) {
|
|
19
|
+
if (settings.signal?.aborted === true) throw stopped(settings.signal, `stopped waiting for ${provider} job ${id}; it may still be running`, {
|
|
20
|
+
jobId: id,
|
|
21
|
+
provider
|
|
22
|
+
});
|
|
23
|
+
const found = await check(id, request);
|
|
24
|
+
if (found !== void 0) return found;
|
|
25
|
+
if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${id} did not finish in time; it may still be running`, {
|
|
26
|
+
jobId: id,
|
|
27
|
+
provider
|
|
28
|
+
});
|
|
29
|
+
await sleep(interval, settings.signal);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Runs an asynchronous job to its result: resumes the job named by `resume`
|
|
34
|
+
* or starts one, checks it until it finishes, then builds the result.
|
|
35
|
+
*
|
|
36
|
+
* Every error after the job has an id carries it as `jobId`, including a
|
|
37
|
+
* timeout or cancellation while waiting, so the caller can resume rather than
|
|
38
|
+
* start a second job. An error that is not a `FieldworkError` becomes
|
|
39
|
+
* `ProviderError` with the original as `cause`.
|
|
40
|
+
*/
|
|
41
|
+
const runJob = async (provider, job, settings) => {
|
|
42
|
+
const id = settings.resume ?? await job.start();
|
|
43
|
+
try {
|
|
44
|
+
return await job.finish(await waitFor(provider, id, job.check, settings), id);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error instanceof FieldworkError) throw withJob(error, id);
|
|
47
|
+
throw new FieldworkError("ProviderError", error instanceof Error ? error.message : String(error), {
|
|
48
|
+
cause: error,
|
|
49
|
+
jobId: id,
|
|
50
|
+
provider
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Sends the POST that creates a job, marked `creates` so a failure after
|
|
56
|
+
* which the provider may have created it is not repeated, reads the reply
|
|
57
|
+
* through `reply`, and returns the job id `idOf` picks from it.
|
|
58
|
+
*
|
|
59
|
+
* Throws `ProviderError` carrying the id as it arrived when the reply has none.
|
|
60
|
+
*/
|
|
61
|
+
const startJob = async (raw, path, request, reply, idOf) => requireJobId(raw.provider, idOf(z.parse(reply, await raw.request("POST", path, {
|
|
62
|
+
...request,
|
|
63
|
+
creates: true
|
|
64
|
+
}))));
|
|
65
|
+
/**
|
|
66
|
+
* Which of `states` a job's reported status is in. `status.original` is the
|
|
67
|
+
* provider's whole response, not the status field alone.
|
|
68
|
+
*
|
|
69
|
+
* Throws `ProviderError` with `jobId`, carrying that response as `cause`, for
|
|
70
|
+
* a status in none of them or a missing one the provider always sends, rather
|
|
71
|
+
* than polling an unknown state until the timeout.
|
|
72
|
+
*/
|
|
73
|
+
const jobState = (provider, id, states, { original, value: status }) => {
|
|
74
|
+
if (status === void 0 && states.missingIsRunning === true) return "running";
|
|
75
|
+
if (status !== void 0) {
|
|
76
|
+
if (states.running.includes(status)) return "running";
|
|
77
|
+
if (states.done.includes(status)) return "done";
|
|
78
|
+
if (states.failed.includes(status)) return "failed";
|
|
79
|
+
}
|
|
80
|
+
throw new FieldworkError("ProviderError", status === void 0 ? `${provider} job ${id} reported no status` : `${provider} job ${id} reported status "${status}", which Fieldwork does not know`, {
|
|
81
|
+
cause: original,
|
|
82
|
+
jobId: id,
|
|
83
|
+
provider
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* A finished job's main payload, which must be there: a run that ends without
|
|
88
|
+
* it has no result to return. `output.original` is the provider's whole
|
|
89
|
+
* response.
|
|
90
|
+
*
|
|
91
|
+
* Throws `JobFailed` with `jobId`, carrying that response as `cause`, when the
|
|
92
|
+
* value is undefined, null or an empty string.
|
|
93
|
+
*/
|
|
94
|
+
const requireOutput = (provider, id, { original, value }) => {
|
|
95
|
+
if (value === void 0 || value === null || value === "") throw new FieldworkError("JobFailed", `${provider} job ${id} finished without output`, {
|
|
96
|
+
cause: original,
|
|
97
|
+
jobId: id,
|
|
98
|
+
provider
|
|
99
|
+
});
|
|
100
|
+
return value;
|
|
101
|
+
};
|
|
102
|
+
export { startJob as i, requireOutput as n, runJob as r, jobState as t };
|