webcrawlerapi-js 1.0.10 → 1.1.1

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 CHANGED
@@ -1,64 +1,190 @@
1
1
  # JS client for WebcrawlerAPI
2
2
 
3
- Official client for [WebcrawlerAPI](https://webcrawlerapi.com/).
3
+ Official client for [WebcrawlerAPI](https://webcrawlerapi.com/). This SDK provides a robust and type-safe way to interact with WebcrawlerAPI's powerful web scraping capabilities, making it easy to extract structured data from any website.
4
4
 
5
- WebcrawlerAPI allows you to extract data from any website with just a simple API call.
5
+ WebcrawlerAPI allows you to extract data from any website with just a simple API call. The service handles all the complexities of web scraping, including JavaScript rendering, proxy rotation, and rate limiting, so you can focus on using the data.
6
6
 
7
7
  ## Preparation
8
8
  1. Register to [dashboard|https://dash.webcrawlerapi.com/].
9
9
  2. Get an [Access Key](https://dash.webcrawlerapi.com/access).
10
10
 
11
+ Our dashboard provides comprehensive analytics and monitoring tools to help you track your API usage and optimize your scraping operations.
12
+
11
13
  ## Installation
12
14
  Install WebcrawlerAPI js package:
13
15
 
14
16
  `npm i webcrawlerapi-js`
15
17
 
16
- ## Request example
18
+ The package is regularly updated with new features and improvements to ensure the best possible scraping experience.
19
+
20
+ ## JavaScript Examples
21
+
22
+ ### Synchronous Job
23
+ In this mode, the promise will be resolved when all data is ready. Synchronous jobs are perfect for quick scraping tasks where you need immediate results and don't want to handle polling logic.
17
24
 
18
25
  ```javascript
19
- import { WebcrawlerClient } from "webcrawlerapi-js"
26
+ import webcrawlerapi from "webcrawlerapi-js"
20
27
 
21
28
  async function main() {
22
29
  const client = new WebcrawlerClient(
23
30
  "YOUR API ACCESS KEY HERE",
24
31
  )
25
- // sync way - promise will be resolved with the all the data
26
- const syncJob = await client.crawl({
32
+
33
+ try {
34
+ const syncJob = await client.crawl({
27
35
  "items_limit": 10,
28
36
  "url": "https://stripe.com/",
29
37
  "scrape_type": "markdown"
30
- }
31
- )
32
- for (const item of syncJob.job_items) {
33
- item.getContent().then((content) => {
34
- console.log(content.slice(0, 100));
35
38
  })
39
+
40
+ for (const item of syncJob.job_items) {
41
+ const content = await item.getContent()
42
+ console.log(content.slice(0, 100))
43
+ }
44
+ console.log(syncJob)
45
+
46
+ } catch (error) {
47
+ if (error instanceof webcrawlerapi.WebcrawlerApiError) {
48
+ console.error("Webcrawler error:", error.message)
49
+ }
50
+ return
36
51
  }
37
- console.log(syncJob);
52
+ }
53
+
54
+ main().catch(console.error)
55
+ ```
56
+
57
+ ### Asynchronous Job
58
+ In this mode, you get a job ID immediately and can poll for results. Asynchronous jobs are ideal for large-scale scraping operations where you want to process data in batches or handle long-running tasks efficiently.
38
59
 
39
- // or async - get the job id and then poll the job status and get the data
60
+ ```javascript
61
+ import webcrawlerapi from "webcrawlerapi-js"
40
62
 
41
- const jobWithId = await client.crawlAsync({
63
+ async function main() {
64
+ const client = new WebcrawlerClient(
65
+ "YOUR API ACCESS KEY HERE",
66
+ )
67
+
68
+ try {
69
+ // Get job ID immediately
70
+ const jobWithId = await client.crawlAsync({
42
71
  "items_limit": 10,
43
72
  "url": "https://stripe.com/",
44
73
  "scrape_type": "markdown"
74
+ })
75
+
76
+ // Poll for job completion
77
+ const jobId = jobWithId.id
78
+ let asyncJob = await client.getJob(jobId)
79
+
80
+ // Check job status
81
+ console.log("Job status:", asyncJob.status)
82
+
83
+ // Once complete, access results
84
+ if (asyncJob.status === "completed") {
85
+ for (const item of asyncJob.job_items) {
86
+ const content = await item.getContent()
87
+ console.log(content.slice(0, 100))
88
+ }
45
89
  }
90
+ } catch (error) {
91
+ if (error instanceof webcrawlerapi.WebcrawlerApiError) {
92
+ console.error("Webcrawler error:", error.message)
93
+ }
94
+ }
95
+ }
96
+
97
+ main().catch(console.error)
98
+ ```
99
+
100
+ ## TypeScript Usage
101
+
102
+ The SDK provides full TypeScript support with type safety and error handling. Our TypeScript integration ensures you catch potential issues at compile-time and provides excellent IDE support with autocompletion and inline documentation.
103
+
104
+ ```typescript
105
+ import { WebcrawlerClient, WebcrawlerApiError } from "webcrawlerapi-js"
106
+
107
+ async function main() {
108
+ const client = new WebcrawlerClient(
109
+ "YOUR_API_KEY",
110
+ // Optional base URL, defaults to production API
111
+ "http://localhost:8080"
46
112
  )
47
- // wait for job to complete
48
- const jobId = jobWithId.id;
49
- let asyncJob = await client.getJob(jobId);
50
113
 
51
- console.log(asyncJob);
114
+ try {
115
+ // Basic crawl with markdown
116
+ const syncJob = await client.crawl({
117
+ "items_limit": 2,
118
+ "url": "https://books.toscrape.com/",
119
+ "scrape_type": "markdown"
120
+ })
121
+
122
+ // Type-safe status check
123
+ if (syncJob.status === "done") {
124
+ for (const item of syncJob.job_items) {
125
+ if (item.markdown_content_url) {
126
+ // Access typed properties
127
+ console.log("Status code:", item.page_status_code)
128
+ console.log("Content URL:", item.markdown_content_url)
129
+ }
130
+ }
131
+ }
132
+
133
+ // Using specialized scraper
134
+ const scrapeJob = await client.scrape({
135
+ "crawler_id": "webcrawler/url-to-md",
136
+ "input": {
137
+ "url": "https://books.toscrape.com/"
138
+ }
139
+ })
140
+
141
+ if (scrapeJob.status === "done") {
142
+ const content = scrapeJob.getContent()
143
+ console.log("Scraped content:", content)
144
+ }
145
+
146
+ } catch (error) {
147
+ // Type-safe error handling
148
+ if (error instanceof WebcrawlerApiError) {
149
+ console.error("API Error:", error.errorCode, error.message)
150
+ // errorCode is typed and can be used for specific error handling
151
+ if (error.errorCode === "invalid_request") {
152
+ // Handle invalid request
153
+ }
154
+ }
155
+ }
52
156
  }
53
157
 
54
- main().catch(console.error);
158
+ main().catch(console.error)
55
159
  ```
56
160
 
57
- ## Response example
58
- ```javascript
161
+ ### Error Handling
162
+
163
+ The SDK provides typed error handling through the `WebcrawlerApiError` class. Our error handling system is designed to provide detailed, actionable feedback that helps you quickly identify and resolve issues in your scraping pipeline.
164
+
165
+ ```typescript
166
+ try {
167
+ const syncJob = await client.crawl({
168
+ "items_limit": 2,
169
+ "url": "https://books.toscrape.com/",
170
+ // This will cause an error due to missing scrape_type
171
+ })
172
+ } catch (error) {
173
+ if (error instanceof WebcrawlerApiError) {
174
+ // Typed error properties
175
+ console.error("Error code:", error.errorCode)
176
+ console.error("Error message:", error.message)
177
+ }
178
+ }
179
+ ```
180
+
181
+ ## Response Structure
182
+
183
+ Example of a job response. The response structure is carefully designed to provide comprehensive information about your scraping job, including detailed status updates, timing information, and resource usage metrics.
184
+
185
+ ```json
59
186
  {
60
187
  id: '49c4942b-b7d9-4d62-94b5-b54a3016ac51',
61
- org_id: 'clxsnorta00075wuuqxgzzvxm',
62
188
  url: 'https://stripe.com/',
63
189
  scrape_type: 'markdown',
64
190
  whitelist_regexp: '',
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "webcrawlerapi-js",
3
- "version": "1.0.10",
3
+ "version": "1.1.1",
4
4
 
5
5
  "description": "JS client for WebcrawlerAPI",
6
- "main": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
6
+ "main": "./dist/api.js",
7
+ "types": "./dist/@types/api.d.ts",
8
8
  "scripts": {
9
9
  "build": "tsc --outDir dist/"
10
10
  },
@@ -1,11 +1,14 @@
1
1
  import {CrawlRequest, Job, JobId, ScrapeRequest, ScrapeResponse} from "./model";
2
2
  import { JobStatus } from "./constants";
3
- import { WebcrawlerApiError, createErrorFromResponse } from "./errors";
3
+ import { WebcrawlerApiError, createErrorFromResponse, ErrorResponse } from "./errors";
4
4
 
5
5
  const BASE_PATH = "https://api.webcrawlerapi.com"
6
6
  const initialPullDelayMs = 2000
7
7
  const MaxPullRetries = 100
8
8
 
9
+ export { WebcrawlerApiError, JobStatus };
10
+ export * from "./model";
11
+
9
12
  export class WebcrawlerClient {
10
13
  protected apiVersion: string = "v1";
11
14
  protected apiKey: string
@@ -206,7 +209,7 @@ export class WebcrawlerClient {
206
209
 
207
210
  if (!response.ok) {
208
211
  try {
209
- const errorData = await response.json();
212
+ const errorData = await response.json() as ErrorResponse;
210
213
  throw createErrorFromResponse(response, errorData);
211
214
  } catch (e) {
212
215
  if (e instanceof WebcrawlerApiError) {
package/tsconfig.json CHANGED
@@ -1,15 +1,21 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "declaration": true,
4
- "target": "es6",
3
+ "lib": [
4
+ "es2021"
5
+ ],
5
6
  "module": "commonjs",
6
- "noImplicitAny": true,
7
+ "target": "es2021",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true,
7
12
  "outDir": "dist",
8
- "rootDir": ".",
9
- "typeRoots": [
10
- "node_modules/@types"
11
- ]
13
+ "declarationDir": "dist/@types",
14
+ "declaration": true
12
15
  },
16
+ "include": [
17
+ "src/**/*"
18
+ ],
13
19
  "exclude": [
14
20
  "dist",
15
21
  "node_modules"
package/dist/api.d.ts DELETED
@@ -1,15 +0,0 @@
1
- import { CrawlRequest, Job, JobId, ScrapeRequest, ScrapeResponse } from "./model";
2
- export declare class WebcrawlerClient {
3
- protected apiVersion: string;
4
- protected apiKey: string;
5
- protected basePath: string;
6
- constructor(apiKey: string, basePath?: string, apiVersion?: string);
7
- scrapeAsync(scrapeRequest: ScrapeRequest): Promise<JobId>;
8
- scrapeWithMeta(scrapeRequest: ScrapeRequest, maxPollingRetries?: number): Promise<ScrapeResponse>;
9
- scrape(scrapeRequest: ScrapeRequest, maxPollingRetries?: number): Promise<any>;
10
- getScrapeResult(scrapeID: string): Promise<ScrapeResponse>;
11
- crawl(crawlRequest: CrawlRequest): Promise<Job>;
12
- crawlAsync(crawlRequest: CrawlRequest): Promise<JobId>;
13
- getJob(jobID: string): Promise<Job>;
14
- private sendRequest;
15
- }
@@ -1,16 +0,0 @@
1
- export interface ConfigurationParameters {
2
- apiKey?: string;
3
- basePath?: string;
4
- apiVersion?: string;
5
- }
6
- export declare class Configuration {
7
- /**
8
- * Base options for http call
9
- */
10
- baseOptions?: any;
11
- /**
12
- * API version, for example: "v1"
13
- */
14
- apiVersion: string;
15
- constructor(param?: ConfigurationParameters);
16
- }
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Configuration = void 0;
4
- const packageJson = require("../package.json");
5
- class Configuration {
6
- constructor(param = {}) {
7
- /**
8
- * API version, for example: "v1"
9
- */
10
- this.apiVersion = "v1";
11
- this.apiVersion = param.apiVersion;
12
- if (!this.baseOptions) {
13
- this.baseOptions = {};
14
- }
15
- this.baseOptions = {
16
- headers: Object.assign({ 'User-Agent': `webcrawlerapi-js/${packageJson.version}`, 'Content-Type': 'application/json' }, this.baseOptions.headers)
17
- };
18
- }
19
- }
20
- exports.Configuration = Configuration;
@@ -1,13 +0,0 @@
1
- export declare const JobStatus: {
2
- readonly IN_PROGRESS: "in_progress";
3
- readonly NEW: "new";
4
- readonly DONE: "done";
5
- };
6
- export declare const HttpStatus: {
7
- readonly OK: 200;
8
- readonly BAD_REQUEST: 400;
9
- readonly UNAUTHORIZED: 401;
10
- readonly FORBIDDEN: 403;
11
- readonly NOT_FOUND: 404;
12
- readonly INTERNAL_SERVER_ERROR: 500;
13
- };
package/dist/constants.js DELETED
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpStatus = exports.JobStatus = void 0;
4
- exports.JobStatus = {
5
- IN_PROGRESS: 'in_progress',
6
- NEW: 'new',
7
- DONE: 'done'
8
- };
9
- exports.HttpStatus = {
10
- OK: 200,
11
- BAD_REQUEST: 400,
12
- UNAUTHORIZED: 401,
13
- FORBIDDEN: 403,
14
- NOT_FOUND: 404,
15
- INTERNAL_SERVER_ERROR: 500
16
- };
package/dist/errors.d.ts DELETED
@@ -1,12 +0,0 @@
1
- export declare class WebcrawlerApiError extends Error {
2
- errorCode: string;
3
- errorMessage: string;
4
- statusCode?: number;
5
- constructor(errorCode: string, errorMessage: string, statusCode?: number);
6
- }
7
- export interface ErrorResponse {
8
- error_code?: string;
9
- error_message?: string;
10
- error?: string;
11
- }
12
- export declare function createErrorFromResponse(response: Response, data: ErrorResponse): WebcrawlerApiError;
package/dist/errors.js DELETED
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebcrawlerApiError = void 0;
4
- exports.createErrorFromResponse = createErrorFromResponse;
5
- class WebcrawlerApiError extends Error {
6
- constructor(errorCode, errorMessage, statusCode) {
7
- super(errorMessage);
8
- this.name = 'WebcrawlerApiError';
9
- this.errorCode = errorCode;
10
- this.errorMessage = errorMessage;
11
- this.statusCode = statusCode;
12
- }
13
- }
14
- exports.WebcrawlerApiError = WebcrawlerApiError;
15
- function createErrorFromResponse(response, data) {
16
- const errorCode = data.error_code || 'unknown_error';
17
- const errorMessage = data.error_message || data.error || 'Unknown error';
18
- return new WebcrawlerApiError(errorCode, errorMessage, response.status);
19
- }
package/dist/model.d.ts DELETED
@@ -1,62 +0,0 @@
1
- export interface ScrapeRequest {
2
- input: any;
3
- crawler_id: string;
4
- max_retries?: number;
5
- debug?: boolean;
6
- omit_cache?: boolean;
7
- }
8
- export interface JobId {
9
- id: string;
10
- }
11
- export interface ScrapeResponse {
12
- id: string;
13
- url: string;
14
- status: any;
15
- page_status_code: number;
16
- created_at: string;
17
- structured_data: any;
18
- recommended_pull_delay_ms: number;
19
- }
20
- export interface CrawlRequest {
21
- url: string;
22
- items_limit?: number;
23
- scrape_type?: string;
24
- whitelist_regexp?: string;
25
- blacklist_regexp?: string;
26
- allow_subdomains?: boolean;
27
- webhook_url?: string;
28
- }
29
- export interface Job {
30
- id: string;
31
- org_id: string;
32
- url: string;
33
- status: string;
34
- scrape_type: string;
35
- whitelist_regexp: string;
36
- blacklist_regexp: string;
37
- allow_subdomains: boolean;
38
- items_limit: number;
39
- created_at: string;
40
- finished_at: string;
41
- updated_at: string;
42
- webhook_url: string;
43
- recommended_pull_delay_ms: number;
44
- job_items: JobItem[];
45
- }
46
- export interface JobItem {
47
- id: string;
48
- job_id: string;
49
- original_url: string;
50
- page_status_code: number;
51
- markdown_content_url: string;
52
- status: string;
53
- title: string;
54
- last_error: string;
55
- created_at: string;
56
- updated_at: string;
57
- cost: number;
58
- referred_url: string;
59
- raw_content_url?: string;
60
- cleaned_content_url?: string;
61
- getContent(): Promise<string | null>;
62
- }
package/dist/model.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from "./api";
2
- export * from "./model";
3
- export * from "./constants";
4
- export * from "./errors";
File without changes
File without changes
File without changes