@howells/fieldwork-sdk 0.0.0-stage → 0.2.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.
@@ -0,0 +1,78 @@
1
+ import { n as AnyAdapter, u as Capability } from "./adapter-C_kRm6TT.js";
2
+ type FieldworkErrorCode =
3
+ /** The adapter's provider does not offer this capability. */
4
+ "Unsupported" |
5
+ /** The API key is missing or the provider rejected it. */
6
+ "Unauthorized" |
7
+ /** The provider refused the request because of a rate or plan limit. */
8
+ "RateLimited" | "NotFound" |
9
+ /** The provider rejected the request as malformed. */
10
+ "InvalidRequest" |
11
+ /** An asynchronous job finished without a result. */
12
+ "JobFailed" | "Timeout" | "Aborted" |
13
+ /** Any other provider failure. */
14
+ "ProviderError";
15
+ interface FieldworkErrorOptions {
16
+ provider?: string;
17
+ status?: number;
18
+ /** Seconds the provider asked to wait before retrying. */
19
+ retryAfter?: number;
20
+ /** The provider's id for an asynchronous job that was already created. */
21
+ jobId?: string;
22
+ /** Overrides the default, which follows from the code and status. */
23
+ retryable?: boolean;
24
+ cause?: unknown;
25
+ }
26
+ /** The one error type every adapter throws, with a normalized code. */
27
+ declare class FieldworkError extends Error {
28
+ readonly name = "FieldworkError";
29
+ readonly code: FieldworkErrorCode;
30
+ readonly provider?: string;
31
+ readonly status?: number;
32
+ readonly retryAfter?: number;
33
+ /**
34
+ * The provider's id for an asynchronous job that was already created when
35
+ * the call failed. The job may still be running and billing: pass this id
36
+ * as `resume` to wait for it again rather than starting another.
37
+ */
38
+ readonly jobId?: string;
39
+ /**
40
+ * Whether repeating the same call can succeed. False whenever `jobId` is
41
+ * set, because repeating the call would start a second job; resume it.
42
+ */
43
+ readonly retryable: boolean;
44
+ constructor(code: FieldworkErrorCode, message: string, options?: FieldworkErrorOptions);
45
+ /** The fields an agent or a log needs, without the provider's response. */
46
+ toJSON(): {
47
+ name: string;
48
+ code: FieldworkErrorCode;
49
+ message: string;
50
+ provider: string | undefined;
51
+ status: number | undefined;
52
+ retryable: boolean;
53
+ retryAfter: number | undefined;
54
+ jobId: string | undefined;
55
+ };
56
+ }
57
+ interface FieldworkOptions<A extends AnyAdapter> {
58
+ adapter: A;
59
+ }
60
+ interface FieldworkBase<A extends AnyAdapter> {
61
+ /** The adapter's name, such as "firecrawl" or "router". */
62
+ readonly provider: A["name"];
63
+ /** Which capabilities this instance can call. */
64
+ readonly capabilities: Readonly<Record<Capability, boolean>>;
65
+ /** The provider's HTTP API, for anything Fieldwork does not wrap. */
66
+ readonly raw: A["raw"];
67
+ supports(capability: Capability): boolean;
68
+ /** The provider that serves a capability, or undefined when none does. */
69
+ providerFor(capability: Capability): string | undefined;
70
+ }
71
+ /**
72
+ * A Fieldwork instance has exactly the methods its adapter's provider offers.
73
+ * `new Fieldwork({ adapter: tavily() }).act(...)` does not compile, because
74
+ * Tavily has no browser.
75
+ */
76
+ type Fieldwork<A extends AnyAdapter> = FieldworkBase<A> & Readonly<A["operations"]>;
77
+ declare const Fieldwork: new <A extends AnyAdapter>(options: FieldworkOptions<A>) => Fieldwork<A>;
78
+ export { FieldworkErrorCode as i, FieldworkOptions as n, FieldworkError as r, Fieldwork as t };
@@ -0,0 +1,130 @@
1
+ import { C as SearchResponse, E as SiteMap, S as Research, _ as JsonSchema, a as RawClient, b as Product, f as Crawl, h as Extraction, l as CallOptions, p as DocumentInput, s as ActResult, t as Adapter, v as Page, y as ParsedDocument } from "./adapter-C_kRm6TT.js";
2
+ import { t as Json } from "./util-D0PLE6Rl.js";
3
+ export interface FirecrawlConfig {
4
+ /** Defaults to the FIRECRAWL_API_KEY environment variable. */
5
+ apiKey?: string;
6
+ baseUrl?: string;
7
+ fetch?: typeof fetch;
8
+ }
9
+ /** Page-fetching settings Firecrawl applies before reading. */
10
+ export interface FirecrawlPageOptions extends CallOptions {
11
+ onlyMainContent?: boolean;
12
+ includeTags?: string[];
13
+ excludeTags?: string[];
14
+ /** Milliseconds of cache Firecrawl may use; 0 forces a live fetch. */
15
+ maxAge?: number;
16
+ /** Milliseconds to wait for the page before reading it. */
17
+ waitFor?: number;
18
+ mobile?: boolean;
19
+ proxy?: "basic" | "enhanced" | "auto";
20
+ location?: {
21
+ country?: string;
22
+ languages?: string[];
23
+ };
24
+ /** Clicks, scrolls, waits and scripts to run before reading. */
25
+ actions?: Json[];
26
+ }
27
+ export interface FirecrawlSearchOptions extends CallOptions {
28
+ /** Results per source; Firecrawl allows up to 100. */
29
+ limit?: number;
30
+ sources?: ("web" | "news" | "images")[];
31
+ categories?: ("github" | "research" | "pdf")[];
32
+ /** Hosts only; Firecrawl does not filter by path. */
33
+ includeDomains?: string[];
34
+ excludeDomains?: string[];
35
+ country?: string;
36
+ location?: string;
37
+ /** Google time filter, such as "qdr:w" for the past week. */
38
+ tbs?: string;
39
+ /** Include each result's page text as Markdown. */
40
+ content?: boolean;
41
+ }
42
+ export interface FirecrawlReadOptions extends FirecrawlPageOptions {
43
+ /** Extra formats beside Markdown. */
44
+ include?: ("html" | "rawHtml" | "links" | "images" | "screenshot" | "summary")[];
45
+ }
46
+ export interface FirecrawlExtractOptions extends FirecrawlPageOptions {
47
+ schema: JsonSchema;
48
+ prompt?: string;
49
+ }
50
+ export interface FirecrawlMapOptions extends CallOptions {
51
+ limit?: number;
52
+ /** Order links by relevance to this text. */
53
+ search?: string;
54
+ sitemap?: "skip" | "include" | "only";
55
+ includeSubdomains?: boolean;
56
+ /** Firecrawl defaults to true, which merges URLs that differ only by query. */
57
+ ignoreQueryParameters?: boolean;
58
+ }
59
+ export interface FirecrawlCrawlOptions extends CallOptions {
60
+ limit?: number;
61
+ /** Plain-words crawl instructions. */
62
+ prompt?: string;
63
+ includePaths?: string[];
64
+ excludePaths?: string[];
65
+ maxDiscoveryDepth?: number;
66
+ sitemap?: "skip" | "include" | "only";
67
+ crawlEntireDomain?: boolean;
68
+ allowSubdomains?: boolean;
69
+ allowExternalLinks?: boolean;
70
+ ignoreQueryParameters?: boolean;
71
+ delay?: number;
72
+ maxConcurrency?: number;
73
+ scrapeOptions?: Json;
74
+ /** Milliseconds between status checks. */
75
+ interval?: number;
76
+ /**
77
+ * The id of a job that timed out or was cancelled, from the error's
78
+ * `jobId`. Waits for that job instead of starting a new one.
79
+ */
80
+ resume?: string;
81
+ }
82
+ export interface FirecrawlResearchOptions extends CallOptions {
83
+ schema?: JsonSchema;
84
+ /** Pages to start from. */
85
+ urls?: string[];
86
+ /** Visit only `urls`. */
87
+ strictConstrainToURLs?: boolean;
88
+ /** Credit cap for the run. */
89
+ maxCredits?: number;
90
+ model?: "spark-2" | "spark-1-mini" | "spark-1-pro";
91
+ effort?: "low" | "medium" | "high";
92
+ interval?: number;
93
+ /**
94
+ * The id of a job that timed out or was cancelled, from the error's
95
+ * `jobId`. Waits for that job instead of starting a new one.
96
+ */
97
+ resume?: string;
98
+ }
99
+ export interface FirecrawlActOptions extends CallOptions {
100
+ language?: "node" | "python" | "bash";
101
+ /** Seconds the browser session may live. */
102
+ ttl?: number;
103
+ profile?: {
104
+ name: string;
105
+ saveChanges?: boolean;
106
+ };
107
+ }
108
+ export interface FirecrawlParseOptions extends CallOptions {
109
+ /** "fast" reads embedded text only, "ocr" always runs OCR, "auto" falls back to OCR. */
110
+ mode?: "auto" | "fast" | "ocr";
111
+ maxPages?: number;
112
+ /** Return one Markdown entry per physical page. */
113
+ pages?: boolean;
114
+ /** Return layout blocks with positions. */
115
+ blocks?: boolean;
116
+ }
117
+ export interface FirecrawlOperations {
118
+ search(query: string, options?: FirecrawlSearchOptions): Promise<SearchResponse>;
119
+ read(url: string, options?: FirecrawlReadOptions): Promise<Page>;
120
+ extract<T = unknown>(url: string, options: FirecrawlExtractOptions): Promise<Extraction<T>>;
121
+ /** Reads product and variant data from the page's structured data, without a model. */
122
+ product(url: string, options?: FirecrawlPageOptions): Promise<Product>;
123
+ map(url: string, options?: FirecrawlMapOptions): Promise<SiteMap>;
124
+ crawl(url: string, options?: FirecrawlCrawlOptions): Promise<Crawl>;
125
+ research<T = unknown>(question: string, options?: FirecrawlResearchOptions): Promise<Research<T>>;
126
+ /** Runs a script in a fresh browser session, then closes it. */
127
+ act(code: string, options?: FirecrawlActOptions): Promise<ActResult>;
128
+ parse(document: DocumentInput, options?: FirecrawlParseOptions): Promise<ParsedDocument>;
129
+ }
130
+ export declare function firecrawl(config?: FirecrawlConfig): Adapter<"firecrawl", FirecrawlOperations, RawClient>;
@@ -0,0 +1,315 @@
1
+ import { t as defineAdapter } from "./adapter-D-6-GFhJ.js";
2
+ import { r as withJob, t as FieldworkError } from "./errors-pzPMh82H.js";
3
+ import { a as list, c as record, d as strings, f as text, g as requireKey, h as poll, i as compact, l as requireId, m as createRawClient, o as num, t as callSettings, u as scalar } from "./util-DgcIZI2K.js";
4
+ // src/adapters/firecrawl.ts
5
+ function pageBody(o) {
6
+ return compact({
7
+ onlyMainContent: o.onlyMainContent,
8
+ includeTags: o.includeTags,
9
+ excludeTags: o.excludeTags,
10
+ maxAge: o.maxAge,
11
+ waitFor: o.waitFor,
12
+ mobile: o.mobile,
13
+ proxy: o.proxy,
14
+ location: o.location,
15
+ actions: o.actions
16
+ });
17
+ }
18
+ function toPage(data, fallbackUrl, raw) {
19
+ const metadata = record(data.metadata);
20
+ return compact({
21
+ url: text(metadata.url) ?? text(metadata.sourceURL) ?? fallbackUrl,
22
+ title: text(metadata.title),
23
+ markdown: text(data.markdown),
24
+ html: text(data.html),
25
+ rawHtml: text(data.rawHtml),
26
+ links: strings(data.links),
27
+ images: strings(data.images),
28
+ raw
29
+ });
30
+ }
31
+ function toVariant(value) {
32
+ const variant = record(value);
33
+ const price = record(variant.price);
34
+ const values = record(variant.values);
35
+ return compact({
36
+ id: text(variant.id),
37
+ sku: text(variant.sku),
38
+ title: text(variant.title),
39
+ values: Object.keys(values).length > 0 ? Object.fromEntries(Object.entries(values).map(([k, v]) => [k, scalar(v) ?? ""])) : void 0,
40
+ price: variant.price ? compact({
41
+ amount: text(price.amount) ?? num(price.amount)?.toString(),
42
+ currency: text(price.currency)
43
+ }) : void 0,
44
+ inStock: typeof record(variant.availability).inStock === "boolean" ? record(variant.availability).inStock : void 0,
45
+ images: strings(variant.images)
46
+ });
47
+ }
48
+ const MEDIA_TYPES = new Map(Object.entries({
49
+ pdf: "application/pdf",
50
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
51
+ doc: "application/msword",
52
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
53
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
54
+ html: "text/html",
55
+ csv: "text/csv",
56
+ rtf: "application/rtf",
57
+ epub: "application/epub+zip"
58
+ }));
59
+ function toBlob(data, name) {
60
+ if (data instanceof Blob) return data;
61
+ const extension = name.split(".").pop()?.toLowerCase() ?? "";
62
+ return new Blob([data], { type: MEDIA_TYPES.get(extension) ?? "application/octet-stream" });
63
+ }
64
+ function firecrawl(config = {}) {
65
+ const provider = "firecrawl";
66
+ const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
67
+ const raw = createRawClient({
68
+ provider,
69
+ baseUrl,
70
+ headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "FIRECRAWL_API_KEY")}` },
71
+ fetch: config.fetch
72
+ });
73
+ async function scrape(url, formats, o, call) {
74
+ const response = record(await raw.request("POST", "/scrape", {
75
+ ...call,
76
+ body: {
77
+ url,
78
+ formats,
79
+ ...pageBody(o)
80
+ }
81
+ }));
82
+ return {
83
+ response,
84
+ data: record(response.data)
85
+ };
86
+ }
87
+ return defineAdapter({
88
+ name: provider,
89
+ operations: {
90
+ async search(query, options) {
91
+ const { call, rest: o } = callSettings(options);
92
+ const response = record(await raw.request("POST", "/search", {
93
+ ...call,
94
+ body: compact({
95
+ query,
96
+ limit: o.limit,
97
+ sources: o.sources,
98
+ categories: o.categories,
99
+ includeDomains: o.includeDomains,
100
+ excludeDomains: o.excludeDomains,
101
+ country: o.country,
102
+ location: o.location,
103
+ tbs: o.tbs,
104
+ scrapeOptions: o.content ? { formats: ["markdown"] } : void 0
105
+ })
106
+ }));
107
+ const data = record(response.data);
108
+ return {
109
+ results: [...list(data.web), ...list(data.news)].map((item) => {
110
+ const result = record(item);
111
+ return compact({
112
+ url: text(result.url) ?? "",
113
+ title: text(result.title),
114
+ snippet: text(result.description) ?? text(result.snippet),
115
+ content: text(result.markdown),
116
+ publishedAt: text(result.date)
117
+ });
118
+ }),
119
+ raw: response
120
+ };
121
+ },
122
+ async read(url, options) {
123
+ const { call, rest: o } = callSettings(options);
124
+ const { include, ...page } = o;
125
+ const { response, data } = await scrape(url, ["markdown", ...include ?? []], page, call);
126
+ return toPage(data, url, response);
127
+ },
128
+ async extract(url, options) {
129
+ const { call, rest: o } = callSettings(options);
130
+ const { schema, prompt, ...page } = o;
131
+ const { response, data } = await scrape(url, [compact({
132
+ type: "json",
133
+ schema,
134
+ prompt
135
+ })], page, call);
136
+ if (data.json === void 0) throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}`, {
137
+ provider,
138
+ cause: response
139
+ });
140
+ return {
141
+ data: data.json,
142
+ raw: response
143
+ };
144
+ },
145
+ async product(url, options) {
146
+ const { call, rest: o } = callSettings(options);
147
+ const { response, data } = await scrape(url, ["product"], o, call);
148
+ if (!data.product) throw new FieldworkError("NotFound", `firecrawl found no product on ${url}`, {
149
+ provider,
150
+ cause: response
151
+ });
152
+ const product = record(data.product);
153
+ return compact({
154
+ title: text(product.title),
155
+ brand: text(product.brand),
156
+ category: text(product.category),
157
+ description: text(product.description),
158
+ url: text(product.url),
159
+ variants: list(product.variants).map((variant) => toVariant(variant)),
160
+ raw: response
161
+ });
162
+ },
163
+ async map(url, options) {
164
+ const { call, rest: o } = callSettings(options);
165
+ const response = record(await raw.request("POST", "/map", {
166
+ ...call,
167
+ body: compact({
168
+ url,
169
+ ...o
170
+ })
171
+ }));
172
+ return {
173
+ links: list(response.links).map((item) => {
174
+ if (typeof item === "string") return { url: item };
175
+ const link = record(item);
176
+ return compact({
177
+ url: text(link.url) ?? "",
178
+ title: text(link.title),
179
+ description: text(link.description)
180
+ });
181
+ }),
182
+ raw: response
183
+ };
184
+ },
185
+ async crawl(url, options) {
186
+ const { call, rest: o } = callSettings(options);
187
+ const { interval, resume, ...body } = o;
188
+ const id = resume ?? requireId(provider, record(await raw.request("POST", "/crawl", {
189
+ ...call,
190
+ body: compact({
191
+ url,
192
+ ...body
193
+ })
194
+ })).id);
195
+ const first = await poll(provider, id, async () => {
196
+ const status = record(await raw.request("GET", `/crawl/${id}`, { signal: call.signal }));
197
+ if (status.status === "failed" || status.status === "cancelled") throw new FieldworkError("JobFailed", `firecrawl crawl ${id} ended ${text(status.status) ?? "unknown"}`, {
198
+ provider,
199
+ cause: status
200
+ });
201
+ return status.status === "completed" ? status : void 0;
202
+ }, {
203
+ ...call,
204
+ interval
205
+ });
206
+ const batches = [first];
207
+ let next = text(first.next);
208
+ while (next) {
209
+ const nextUrl = new URL(next);
210
+ const path = nextUrl.pathname.slice(new URL(baseUrl).pathname.replace(/\/$/u, "").length) + nextUrl.search;
211
+ const batch = record(await raw.request("GET", path, { signal: call.signal }).catch((error) => {
212
+ throw withJob(error, id);
213
+ }));
214
+ batches.push(batch);
215
+ next = text(batch.next);
216
+ }
217
+ return {
218
+ pages: batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), url, item))),
219
+ raw: batches
220
+ };
221
+ },
222
+ async research(question, options) {
223
+ const { call, rest: o } = callSettings(options);
224
+ const { interval, resume, ...body } = o;
225
+ const id = resume ?? requireId(provider, record(await raw.request("POST", "/agent", {
226
+ ...call,
227
+ body: compact({
228
+ prompt: question,
229
+ ...body
230
+ })
231
+ })).id);
232
+ const run = await poll(provider, id, async () => {
233
+ const status = record(await raw.request("GET", `/agent/${id}`, { signal: call.signal }));
234
+ if (status.status === "failed") throw new FieldworkError("JobFailed", `firecrawl research run ${id} failed: ${text(status.error) ?? "no reason given"}`, {
235
+ provider,
236
+ cause: status
237
+ });
238
+ return status.status === "completed" ? status : void 0;
239
+ }, {
240
+ ...call,
241
+ interval
242
+ });
243
+ return {
244
+ id,
245
+ output: run.data,
246
+ sources: [],
247
+ raw: run
248
+ };
249
+ },
250
+ async act(code, options) {
251
+ const { call, rest: o } = callSettings(options);
252
+ const session = record(await raw.request("POST", "/interact", {
253
+ ...call,
254
+ body: compact({
255
+ ttl: o.ttl,
256
+ activityTtl: o.ttl,
257
+ profile: o.profile
258
+ })
259
+ }));
260
+ const id = requireId(provider, session.id);
261
+ try {
262
+ const result = record(await raw.request("POST", `/interact/${id}/execute`, {
263
+ ...call,
264
+ body: compact({
265
+ code,
266
+ language: o.language ?? "node",
267
+ timeout: call.timeout ? Math.ceil(call.timeout / 1e3) : void 0
268
+ })
269
+ }));
270
+ return compact({
271
+ stdout: text(result.stdout) ?? "",
272
+ stderr: text(result.stderr) ?? "",
273
+ result: result.result === "" ? void 0 : result.result,
274
+ exitCode: num(result.exitCode),
275
+ raw: result
276
+ });
277
+ } finally {
278
+ await raw.request("DELETE", `/interact/${id}`).catch((error) => error);
279
+ }
280
+ },
281
+ async parse(document, options) {
282
+ const { call, rest: o } = callSettings(options);
283
+ const parser = compact({
284
+ type: "pdf",
285
+ mode: o.mode,
286
+ maxPages: o.maxPages,
287
+ pages: o.pages,
288
+ blocks: o.blocks
289
+ });
290
+ const form = new FormData();
291
+ form.set("options", JSON.stringify({
292
+ formats: ["markdown"],
293
+ parsers: [parser]
294
+ }));
295
+ form.set("file", toBlob(document.data, document.name), document.name);
296
+ const response = record(await raw.request("POST", "/parse", {
297
+ ...call,
298
+ form
299
+ }));
300
+ const data = record(response.data);
301
+ return compact({
302
+ markdown: text(data.markdown) ?? "",
303
+ pages: Array.isArray(data.pages) ? list(data.pages).map((page) => ({
304
+ pageNumber: Number(record(page).pageNumber),
305
+ markdown: text(record(page).markdown) ?? ""
306
+ })) : void 0,
307
+ blocks: Array.isArray(data.blocks) ? data.blocks : void 0,
308
+ raw: response
309
+ });
310
+ }
311
+ },
312
+ raw
313
+ });
314
+ }
315
+ export { firecrawl };
@@ -0,0 +1,18 @@
1
+ import { C as SearchResponse, E as SiteMap, S as Research, T as SiteLink, _ as JsonSchema, a as RawClient, b as Product, c as CAPABILITIES, d as Citation, f as Crawl, g as FieldSource, h as Extraction, i as defineAdapter, l as CallOptions, m as DocumentPage, n as AnyAdapter, o as RequestOptions, p as DocumentInput, r as Operations, s as ActResult, t as Adapter, u as Capability, v as Page, w as SearchResult, x as ProductVariant, y as ParsedDocument } from "./adapter-C_kRm6TT.js";
2
+ import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-nPzWEelg.js";
3
+ type Routes = Partial<Record<Capability, AnyAdapter>>;
4
+ /** Each route must name an adapter whose provider offers that capability. */
5
+ type ValidRoutes<R extends Routes> = { [C in keyof R]: C extends Capability ? R[C] extends {
6
+ operations: Record<C, unknown>;
7
+ } ? R[C] : `${R[C] extends AnyAdapter ? R[C]["name"] : "this adapter"} does not offer ${C}` : never; };
8
+ type RouterOperations<R extends Routes> = { [C in keyof R & Capability]: R[C] extends {
9
+ operations: Record<C, infer Op extends (...args: never[]) => Promise<unknown>>;
10
+ } ? Op : never; };
11
+ type RouterRaw<R extends Routes> = { [C in keyof R & Capability as R[C] extends AnyAdapter ? R[C]["name"] : never]: R[C] extends AnyAdapter ? R[C]["raw"] : never; };
12
+ /**
13
+ * One adapter per capability: `router({ search: parallel(), read: firecrawl() })`.
14
+ * Each capability goes to exactly the adapter named for it; a capability with
15
+ * no route is unsupported, and nothing falls back to another provider.
16
+ */
17
+ export declare function router<const R extends Routes>(routes: R & ValidRoutes<R>): Adapter<"router", RouterOperations<R>, RouterRaw<R>>;
18
+ export { ActResult, type Adapter, type AnyAdapter, CAPABILITIES, CallOptions, Capability, Citation, Crawl, DocumentInput, DocumentPage, Extraction, FieldSource, Fieldwork, FieldworkError, type FieldworkErrorCode, type FieldworkOptions, JsonSchema, type Operations, Page, ParsedDocument, Product, ProductVariant, type RawClient, type RequestOptions, Research, type Routes, SearchResponse, SearchResult, SiteLink, SiteMap, defineAdapter };
package/dist/index.js ADDED
@@ -0,0 +1,73 @@
1
+ import { t as defineAdapter } from "./adapter-D-6-GFhJ.js";
2
+ import { t as FieldworkError } from "./errors-pzPMh82H.js";
3
+ // src/types.ts
4
+ /** Every capability Fieldwork knows. An adapter implements a subset. */
5
+ const CAPABILITIES = [
6
+ "search",
7
+ "read",
8
+ "extract",
9
+ "product",
10
+ "map",
11
+ "crawl",
12
+ "research",
13
+ "act",
14
+ "parse"
15
+ ];
16
+ // src/fieldwork.ts
17
+ var FieldworkClient = class {
18
+ provider;
19
+ capabilities;
20
+ raw;
21
+ #providers;
22
+ constructor(options) {
23
+ const { adapter } = options;
24
+ const operations = adapter.operations;
25
+ this.provider = adapter.name;
26
+ this.raw = adapter.raw;
27
+ this.#providers = adapter.providers ?? {};
28
+ const capabilities = {};
29
+ const self = this;
30
+ for (const capability of CAPABILITIES) {
31
+ const operation = operations[capability];
32
+ capabilities[capability] = typeof operation === "function";
33
+ self[capability] = typeof operation === "function" ? operation.bind(operations) : async () => {
34
+ throw new FieldworkError("Unsupported", `${adapter.name} does not offer ${capability}`, { provider: adapter.name });
35
+ };
36
+ }
37
+ this.capabilities = Object.freeze(capabilities);
38
+ }
39
+ supports(capability) {
40
+ return this.capabilities[capability];
41
+ }
42
+ providerFor(capability) {
43
+ if (!this.capabilities[capability]) return;
44
+ return this.#providers[capability] ?? this.provider;
45
+ }
46
+ };
47
+ const Fieldwork = FieldworkClient;
48
+ // src/router.ts
49
+ /**
50
+ * One adapter per capability: `router({ search: parallel(), read: firecrawl() })`.
51
+ * Each capability goes to exactly the adapter named for it; a capability with
52
+ * no route is unsupported, and nothing falls back to another provider.
53
+ */
54
+ function router(routes) {
55
+ const operations = {};
56
+ const raw = {};
57
+ const providers = {};
58
+ for (const [capability, adapter] of Object.entries(routes)) {
59
+ if (!adapter) continue;
60
+ const operation = adapter.operations[capability];
61
+ if (typeof operation !== "function") throw new FieldworkError("Unsupported", `${adapter.name} does not offer ${capability}`, { provider: adapter.name });
62
+ operations[capability] = operation.bind(adapter.operations);
63
+ providers[capability] = adapter.name;
64
+ raw[adapter.name] = adapter.raw;
65
+ }
66
+ return defineAdapter({
67
+ name: "router",
68
+ operations,
69
+ raw,
70
+ providers
71
+ });
72
+ }
73
+ export { CAPABILITIES, Fieldwork, FieldworkError, defineAdapter, router };
@@ -0,0 +1,61 @@
1
+ import { C as SearchResponse, S as Research, _ as JsonSchema, a as RawClient, h as Extraction, l as CallOptions, t as Adapter, v as Page } from "./adapter-C_kRm6TT.js";
2
+ export interface ParallelConfig {
3
+ /** Defaults to the PARALLEL_API_KEY environment variable. */
4
+ apiKey?: string;
5
+ baseUrl?: string;
6
+ fetch?: typeof fetch;
7
+ }
8
+ export type ParallelProcessor = "lite" | "base" | "core" | "core2x" | "pro" | "ultra" | "ultra2x" | "ultra4x" | "ultra8x";
9
+ interface ParallelSourcePolicy {
10
+ /** Domains or domain/path prefixes, without a scheme. */
11
+ includeDomains?: string[];
12
+ excludeDomains?: string[];
13
+ /** YYYY-MM-DD. */
14
+ publishedAfter?: string;
15
+ }
16
+ export interface ParallelSearchOptions extends CallOptions, ParallelSourcePolicy {
17
+ /** What the search is for, in plain words. Defaults to the query. */
18
+ objective?: string;
19
+ /** Several keyword queries; defaults to the query alone. */
20
+ queries?: string[];
21
+ mode?: "turbo" | "fast" | "basic" | "advanced";
22
+ limit?: number;
23
+ /** Cap on the total characters of excerpts returned. */
24
+ maxCharsTotal?: number;
25
+ }
26
+ export interface ParallelReadOptions extends CallOptions {
27
+ /** Return passages for this objective as `excerpts`. */
28
+ objective?: string;
29
+ queries?: string[];
30
+ /** Seconds of cache Parallel may use; the minimum is 600. */
31
+ maxAgeSeconds?: number;
32
+ }
33
+ export interface ParallelExtractOptions extends CallOptions {
34
+ schema: JsonSchema;
35
+ prompt?: string;
36
+ /** Defaults to "base". */
37
+ processor?: ParallelProcessor;
38
+ /**
39
+ * The id of a job that timed out or was cancelled, from the error's
40
+ * `jobId`. Waits for that job instead of starting a new one.
41
+ */
42
+ resume?: string;
43
+ }
44
+ export interface ParallelResearchOptions extends CallOptions, ParallelSourcePolicy {
45
+ schema?: JsonSchema;
46
+ /** Defaults to "base". */
47
+ processor?: ParallelProcessor;
48
+ /**
49
+ * The id of a job that timed out or was cancelled, from the error's
50
+ * `jobId`. Waits for that job instead of starting a new one.
51
+ */
52
+ resume?: string;
53
+ }
54
+ export interface ParallelOperations {
55
+ search(query: string, options?: ParallelSearchOptions): Promise<SearchResponse>;
56
+ read(url: string, options?: ParallelReadOptions): Promise<Page>;
57
+ extract<T = unknown>(url: string, options: ParallelExtractOptions): Promise<Extraction<T>>;
58
+ research<T = unknown>(question: string, options?: ParallelResearchOptions): Promise<Research<T>>;
59
+ }
60
+ export declare function parallel(config?: ParallelConfig): Adapter<"parallel", ParallelOperations, RawClient>;
61
+ export {};