stophy 1.2.2 → 1.4.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/dist/index.js CHANGED
@@ -1,3 +1,110 @@
1
+ // src/bind.ts
2
+ function post(path, call) {
3
+ return (body, options) => call({ method: "POST", path, body, options });
4
+ }
5
+ function postOptional(path, call) {
6
+ return (body, options) => call({ method: "POST", path, body: body ?? {}, options });
7
+ }
8
+ function send(method, path, call) {
9
+ return (input, options) => call({ method, ...fillPath(path, input), options });
10
+ }
11
+ function sendOptional(method, path, call) {
12
+ return (input, options) => call({ method, ...fillPath(path, input ?? {}), options });
13
+ }
14
+ function sendEmpty(method, path, call) {
15
+ return (options) => call({ method, path, options });
16
+ }
17
+ function fillPath(template, input) {
18
+ const used = /* @__PURE__ */ new Set();
19
+ const path = template.replaceAll(/\{(\w+)\}/g, (_, name) => {
20
+ const value = input[name];
21
+ if (value === void 0) throw new TypeError(`Missing ${name} for ${template}`);
22
+ used.add(name);
23
+ return encodeURIComponent(String(value));
24
+ });
25
+ const query = Object.fromEntries(Object.entries(input).filter(([key]) => !used.has(key)));
26
+ return { path, query };
27
+ }
28
+
29
+ // src/generated/surface.gen.ts
30
+ function bindSurface(call) {
31
+ return {
32
+ extract: Object.assign(postOptional("/v1/extract", call), {
33
+ result: send("GET", "/v1/extract/{id}", call)
34
+ }),
35
+ signup: Object.assign(postOptional("/v1/signup", call), {
36
+ poll: post("/v1/signup/poll", call)
37
+ }),
38
+ limits: sendEmpty("GET", "/v1/limits", call),
39
+ usage: sendEmpty("GET", "/v1/usage", call),
40
+ logs: sendOptional("GET", "/v1/logs", call),
41
+ key: {
42
+ revoke: sendEmpty("DELETE", "/v1/key", call)
43
+ },
44
+ parsers: sendEmpty("GET", "/v1/parsers", call),
45
+ endpoints: sendEmpty("GET", "/v1/endpoints", call),
46
+ search: Object.assign(post("/v1/search", call), {
47
+ developer: post("/v1/search/developer", call)
48
+ }),
49
+ scrape: post("/v1/scrape", call),
50
+ browser: {
51
+ task: Object.assign(post("/v1/browser/task", call), {
52
+ status: post("/v1/browser/task/status", call)
53
+ })
54
+ },
55
+ parse: postOptional("/v1/parse", call),
56
+ map: post("/v1/map", call),
57
+ crawl: Object.assign(post("/v1/crawl", call), {
58
+ status: send("GET", "/v1/crawl/{id}", call),
59
+ cancel: send("DELETE", "/v1/crawl/{id}", call)
60
+ }),
61
+ batch: {
62
+ scrape: Object.assign(post("/v1/batch/scrape", call), {
63
+ status: send("GET", "/v1/batch/scrape/{id}", call),
64
+ cancel: send("DELETE", "/v1/batch/scrape/{id}", call)
65
+ })
66
+ }
67
+ };
68
+ }
69
+ var Surface = class {
70
+ extract;
71
+ signup;
72
+ limits;
73
+ usage;
74
+ logs;
75
+ key;
76
+ parsers;
77
+ endpoints;
78
+ search;
79
+ scrape;
80
+ browser;
81
+ parse;
82
+ map;
83
+ crawl;
84
+ batch;
85
+ constructor(call) {
86
+ const bound = bindSurface(call);
87
+ this.extract = bound.extract;
88
+ this.signup = bound.signup;
89
+ this.limits = bound.limits;
90
+ this.usage = bound.usage;
91
+ this.logs = bound.logs;
92
+ this.key = bound.key;
93
+ this.parsers = bound.parsers;
94
+ this.endpoints = bound.endpoints;
95
+ this.search = bound.search;
96
+ this.scrape = bound.scrape;
97
+ this.browser = bound.browser;
98
+ this.parse = bound.parse;
99
+ this.map = bound.map;
100
+ this.crawl = bound.crawl;
101
+ this.batch = bound.batch;
102
+ }
103
+ };
104
+
105
+ // package.json
106
+ var version = "1.4.0";
107
+
1
108
  // src/errors.ts
2
109
  var StophyError = class extends Error {
3
110
  code;
@@ -5,6 +112,7 @@ var StophyError = class extends Error {
5
112
  retryAfterSeconds;
6
113
  status;
7
114
  requestId;
115
+ details;
8
116
  constructor(message, options) {
9
117
  super(message);
10
118
  this.name = "StophyError";
@@ -13,6 +121,7 @@ var StophyError = class extends Error {
13
121
  this.retryable = options.retryable;
14
122
  this.retryAfterSeconds = options.retryAfterSeconds;
15
123
  this.requestId = options.requestId;
124
+ this.details = options.details ?? {};
16
125
  }
17
126
  };
18
127
 
@@ -33,415 +142,12 @@ function isRecord(value) {
33
142
  return tagOf(value) === "[object Object]";
34
143
  }
35
144
 
36
- // src/account.ts
37
- function usage(call) {
38
- return call({ method: "GET", path: "/v1/usage" }).then(parseUsage);
39
- }
40
- function logs(call, query) {
41
- const params = {};
42
- if (query?.apiKeyId !== void 0) params.apiKeyId = query.apiKeyId;
43
- if (query?.days !== void 0) params.days = query.days;
44
- if (query?.endpoint !== void 0) params.endpoint = query.endpoint;
45
- if (query?.page !== void 0) params.page = query.page;
46
- return call({ method: "GET", path: "/v1/logs", query: params }).then(parseLogs);
47
- }
48
- function parseUsage(value) {
49
- if (!isRecord(value)) return unexpected("usage");
50
- const balanceMicros = numberField(value, "balanceMicros");
51
- const creditsUsed = numberField(value, "creditsUsed");
52
- const requestCount = numberField(value, "requestCount");
53
- return { balanceMicros, creditsUsed, requestCount };
54
- }
55
- function parseLogs(value) {
56
- if (!isRecord(value) || !Array.isArray(value.logs) || !Array.isArray(value.endpoints)) {
57
- return unexpected("logs");
58
- }
59
- return {
60
- endpoints: value.endpoints.map((item) => {
61
- if (!isString(item)) return unexpected("logs.endpoints");
62
- return item;
63
- }),
64
- logs: value.logs.map(parseLog),
65
- page: numberField(value, "page"),
66
- pageSize: numberField(value, "pageSize"),
67
- total: numberField(value, "total"),
68
- totalPages: numberField(value, "totalPages")
69
- };
70
- }
71
- function parseLog(value) {
72
- if (!isRecord(value)) return unexpected("logs.logs");
73
- return {
74
- apiKeyId: stringOrNull(value, "apiKeyId"),
75
- apiKeyName: stringOrNull(value, "apiKeyName"),
76
- createdAt: stringField(value, "createdAt"),
77
- credits: numberField(value, "credits"),
78
- durationMs: numberOrNull(value, "durationMs"),
79
- endpoint: stringField(value, "endpoint"),
80
- id: stringField(value, "id"),
81
- method: stringField(value, "method"),
82
- response: stringField(value, "response"),
83
- status: numberField(value, "status")
84
- };
85
- }
86
- function numberField(record, field) {
87
- const value = record[field];
88
- if (!isNumber(value)) return unexpected(field);
89
- return value;
90
- }
91
- function numberOrNull(record, field) {
92
- const value = record[field];
93
- if (value === null) return null;
94
- if (!isNumber(value)) return unexpected(field);
95
- return value;
96
- }
97
- function stringField(record, field) {
98
- const value = record[field];
99
- if (!isString(value)) return unexpected(field);
100
- return value;
101
- }
102
- function stringOrNull(record, field) {
103
- const value = record[field];
104
- if (value === null) return null;
105
- if (!isString(value)) return unexpected(field);
106
- return value;
107
- }
108
- function unexpected(field) {
109
- throw new StophyError(`Stophy returned an unexpected ${field}`, {
110
- status: 200,
111
- retryable: false
112
- });
113
- }
114
-
115
- // src/bind.ts
116
- function post(path, call) {
117
- return (body, options) => call({ method: "POST", path, body, options });
118
- }
119
- function postOptional(path, call) {
120
- return (body, options) => call({
121
- method: "POST",
122
- path,
123
- body: body ?? {},
124
- options
125
- });
126
- }
127
- function get(path, call) {
128
- return (options) => call({ method: "GET", path, options });
129
- }
130
-
131
- // src/generated/surface.gen.ts
132
- function bindSurface(call) {
133
- return {
134
- endpoints: get("/v1/endpoints", call),
135
- google: {
136
- search: post("/v1/google/search", call),
137
- news: postOptional("/v1/google/news", call),
138
- images: post("/v1/google/images", call),
139
- suggest: post("/v1/google/suggest", call),
140
- ads: {
141
- search: postOptional("/v1/google/ads/search", call),
142
- ad: postOptional("/v1/google/ads/ad", call),
143
- advertisers: post("/v1/google/ads/advertisers", call)
144
- },
145
- scholar: postOptional("/v1/google/scholar", call),
146
- patents: postOptional("/v1/google/patents", call),
147
- maps: {
148
- search: post("/v1/google/maps/search", call),
149
- place: postOptional("/v1/google/maps/place", call),
150
- reviews: postOptional("/v1/google/maps/reviews", call)
151
- },
152
- trends: {
153
- related: post("/v1/google/trends/related", call),
154
- trending: postOptional("/v1/google/trends/trending", call),
155
- interest: post("/v1/google/trends/interest", call),
156
- regions: post("/v1/google/trends/regions", call)
157
- },
158
- flights: post("/v1/google/flights", call),
159
- hotels: post("/v1/google/hotels", call),
160
- play: {
161
- app: postOptional("/v1/google/play/app", call),
162
- search: post("/v1/google/play/search", call),
163
- reviews: postOptional("/v1/google/play/reviews", call)
164
- }
165
- },
166
- web: {
167
- search: post("/v1/web/search", call),
168
- news: post("/v1/web/news", call),
169
- images: post("/v1/web/images", call),
170
- scrape: postOptional("/v1/web/scrape", call),
171
- parse: post("/v1/web/parse", call),
172
- map: post("/v1/web/map", call),
173
- contacts: post("/v1/web/contacts", call),
174
- crawl: Object.assign(post("/v1/web/crawl", call), {
175
- start: post("/v1/web/crawl/start", call),
176
- status: post("/v1/web/crawl/status", call),
177
- cancel: post("/v1/web/crawl/cancel", call)
178
- }),
179
- batch: Object.assign(post("/v1/web/batch", call), {
180
- status: post("/v1/web/batch/status", call),
181
- cancel: post("/v1/web/batch/cancel", call)
182
- })
183
- },
184
- youtube: {
185
- suggest: post("/v1/youtube/suggest", call),
186
- search: post("/v1/youtube/search", call),
187
- transcript: postOptional("/v1/youtube/transcript", call),
188
- video: postOptional("/v1/youtube/video", call),
189
- comments: postOptional("/v1/youtube/comments", call),
190
- channel: postOptional("/v1/youtube/channel", call),
191
- post: postOptional("/v1/youtube/post", call),
192
- playlist: postOptional("/v1/youtube/playlist", call)
193
- },
194
- reddit: {
195
- search: post("/v1/reddit/search", call),
196
- post: postOptional("/v1/reddit/post", call),
197
- subreddit: post("/v1/reddit/subreddit", call),
198
- user: postOptional("/v1/reddit/user", call),
199
- discussions: postOptional("/v1/reddit/discussions", call),
200
- subreddits: postOptional("/v1/reddit/subreddits", call)
201
- },
202
- instagram: {
203
- comments: postOptional("/v1/instagram/comments", call),
204
- post: postOptional("/v1/instagram/post", call),
205
- profile: Object.assign(postOptional("/v1/instagram/profile", call), {
206
- reels: postOptional("/v1/instagram/profile/reels", call)
207
- }),
208
- transcript: postOptional("/v1/instagram/transcript", call)
209
- },
210
- tiktok: {
211
- profile: postOptional("/v1/tiktok/profile", call),
212
- video: postOptional("/v1/tiktok/video", call),
213
- hashtag: post("/v1/tiktok/hashtag", call),
214
- sound: post("/v1/tiktok/sound", call),
215
- comments: postOptional("/v1/tiktok/comments", call),
216
- search: post("/v1/tiktok/search", call),
217
- transcript: postOptional("/v1/tiktok/transcript", call),
218
- ads: {
219
- search: postOptional("/v1/tiktok/ads/search", call),
220
- ad: postOptional("/v1/tiktok/ads/ad", call)
221
- },
222
- shop: {
223
- search: post("/v1/tiktok/shop/search", call),
224
- products: postOptional("/v1/tiktok/shop/products", call),
225
- product: postOptional("/v1/tiktok/shop/product", call),
226
- reviews: postOptional("/v1/tiktok/shop/reviews", call)
227
- }
228
- },
229
- meta: {
230
- ads: {
231
- page: post("/v1/meta/ads/page", call),
232
- search: post("/v1/meta/ads/search", call),
233
- ad: postOptional("/v1/meta/ads/ad", call)
234
- }
235
- },
236
- linkedin: {
237
- jobs: {
238
- search: postOptional("/v1/linkedin/jobs/search", call),
239
- job: postOptional("/v1/linkedin/jobs/job", call)
240
- },
241
- company: postOptional("/v1/linkedin/company", call),
242
- profile: postOptional("/v1/linkedin/profile", call),
243
- posts: postOptional("/v1/linkedin/posts", call),
244
- ads: {
245
- search: postOptional("/v1/linkedin/ads/search", call),
246
- ad: postOptional("/v1/linkedin/ads/ad", call)
247
- }
248
- },
249
- zillow: {
250
- search: post("/v1/zillow/search", call),
251
- property: postOptional("/v1/zillow/property", call)
252
- },
253
- realtor: {
254
- search: post("/v1/realtor/search", call),
255
- property: postOptional("/v1/realtor/property", call)
256
- },
257
- craigslist: {
258
- search: post("/v1/craigslist/search", call)
259
- },
260
- luma: {
261
- events: post("/v1/luma/events", call),
262
- event: post("/v1/luma/event", call)
263
- },
264
- upwork: {
265
- search: postOptional("/v1/upwork/search", call),
266
- job: postOptional("/v1/upwork/job", call)
267
- },
268
- indeed: {
269
- search: postOptional("/v1/indeed/search", call),
270
- job: postOptional("/v1/indeed/job", call)
271
- },
272
- careers: {
273
- jobs: post("/v1/careers/jobs", call),
274
- job: post("/v1/careers/job", call)
275
- },
276
- glassdoor: {
277
- company: Object.assign(postOptional("/v1/glassdoor/company", call), {
278
- reviews: postOptional("/v1/glassdoor/company/reviews", call),
279
- salaries: postOptional("/v1/glassdoor/company/salaries", call)
280
- })
281
- },
282
- tripadvisor: {
283
- search: post("/v1/tripadvisor/search", call),
284
- place: postOptional("/v1/tripadvisor/place", call),
285
- reviews: postOptional("/v1/tripadvisor/reviews", call)
286
- },
287
- yelp: {
288
- search: post("/v1/yelp/search", call),
289
- business: Object.assign(postOptional("/v1/yelp/business", call), {
290
- reviews: postOptional("/v1/yelp/business/reviews", call)
291
- })
292
- },
293
- booking: {
294
- search: post("/v1/booking/search", call),
295
- hotel: Object.assign(postOptional("/v1/booking/hotel", call), {
296
- reviews: postOptional("/v1/booking/hotel/reviews", call)
297
- })
298
- },
299
- expedia: {
300
- hotels: post("/v1/expedia/hotels", call)
301
- },
302
- amazon: {
303
- search: postOptional("/v1/amazon/search", call),
304
- product: postOptional("/v1/amazon/product", call),
305
- reviews: postOptional("/v1/amazon/reviews", call),
306
- bestsellers: post("/v1/amazon/bestsellers", call),
307
- suggest: post("/v1/amazon/suggest", call)
308
- },
309
- appstore: {
310
- app: postOptional("/v1/appstore/app", call),
311
- search: post("/v1/appstore/search", call),
312
- reviews: postOptional("/v1/appstore/reviews", call),
313
- top: postOptional("/v1/appstore/top", call)
314
- },
315
- pinterest: {
316
- search: post("/v1/pinterest/search", call),
317
- pin: postOptional("/v1/pinterest/pin", call),
318
- board: post("/v1/pinterest/board", call),
319
- profile: postOptional("/v1/pinterest/profile", call)
320
- },
321
- x: {
322
- profile: Object.assign(postOptional("/v1/x/profile", call), {
323
- posts: postOptional("/v1/x/profile/posts", call)
324
- }),
325
- post: postOptional("/v1/x/post", call)
326
- },
327
- threads: {
328
- profile: Object.assign(postOptional("/v1/threads/profile", call), {
329
- posts: postOptional("/v1/threads/profile/posts", call)
330
- }),
331
- post: postOptional("/v1/threads/post", call)
332
- },
333
- trustpilot: {
334
- company: Object.assign(postOptional("/v1/trustpilot/company", call), {
335
- reviews: postOptional("/v1/trustpilot/company/reviews", call)
336
- }),
337
- search: post("/v1/trustpilot/search", call)
338
- },
339
- ebay: {
340
- search: post("/v1/ebay/search", call),
341
- item: postOptional("/v1/ebay/item", call)
342
- },
343
- airbnb: {
344
- search: post("/v1/airbnb/search", call),
345
- listing: postOptional("/v1/airbnb/listing", call),
346
- reviews: postOptional("/v1/airbnb/reviews", call)
347
- },
348
- facebook: {
349
- page: Object.assign(postOptional("/v1/facebook/page", call), {
350
- posts: postOptional("/v1/facebook/page/posts", call)
351
- }),
352
- post: Object.assign(postOptional("/v1/facebook/post", call), {
353
- comments: postOptional("/v1/facebook/post/comments", call)
354
- }),
355
- marketplace: {
356
- search: post("/v1/facebook/marketplace/search", call)
357
- }
358
- },
359
- chatgpt: {
360
- search: post("/v1/chatgpt/search", call)
361
- },
362
- gemini: {
363
- search: post("/v1/gemini/search", call)
364
- }
365
- };
366
- }
367
- var Surface = class {
368
- endpoints;
369
- google;
370
- web;
371
- youtube;
372
- reddit;
373
- instagram;
374
- tiktok;
375
- meta;
376
- linkedin;
377
- zillow;
378
- realtor;
379
- craigslist;
380
- luma;
381
- upwork;
382
- indeed;
383
- careers;
384
- glassdoor;
385
- tripadvisor;
386
- yelp;
387
- booking;
388
- expedia;
389
- amazon;
390
- appstore;
391
- pinterest;
392
- x;
393
- threads;
394
- trustpilot;
395
- ebay;
396
- airbnb;
397
- facebook;
398
- chatgpt;
399
- gemini;
400
- constructor(call) {
401
- const bound = bindSurface(call);
402
- this.endpoints = bound.endpoints;
403
- this.google = bound.google;
404
- this.web = bound.web;
405
- this.youtube = bound.youtube;
406
- this.reddit = bound.reddit;
407
- this.instagram = bound.instagram;
408
- this.tiktok = bound.tiktok;
409
- this.meta = bound.meta;
410
- this.linkedin = bound.linkedin;
411
- this.zillow = bound.zillow;
412
- this.realtor = bound.realtor;
413
- this.craigslist = bound.craigslist;
414
- this.luma = bound.luma;
415
- this.upwork = bound.upwork;
416
- this.indeed = bound.indeed;
417
- this.careers = bound.careers;
418
- this.glassdoor = bound.glassdoor;
419
- this.tripadvisor = bound.tripadvisor;
420
- this.yelp = bound.yelp;
421
- this.booking = bound.booking;
422
- this.expedia = bound.expedia;
423
- this.amazon = bound.amazon;
424
- this.appstore = bound.appstore;
425
- this.pinterest = bound.pinterest;
426
- this.x = bound.x;
427
- this.threads = bound.threads;
428
- this.trustpilot = bound.trustpilot;
429
- this.ebay = bound.ebay;
430
- this.airbnb = bound.airbnb;
431
- this.facebook = bound.facebook;
432
- this.chatgpt = bound.chatgpt;
433
- this.gemini = bound.gemini;
434
- }
435
- };
436
-
437
- // package.json
438
- var version = "1.2.2";
439
-
440
145
  // src/transport.ts
441
146
  var DEFAULT_BASE_URL = "https://api.stophy.dev";
442
147
  var DEFAULT_TIMEOUT_MS = 7e4;
443
148
  var MAX_RETRY_WAIT_SECONDS = 60;
444
149
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
150
+ var JOB_STARTS = /* @__PURE__ */ new Set(["/v1/batch/scrape", "/v1/crawl"]);
445
151
  var USER_AGENT = `stophy-typescript/${version}`;
446
152
  function createCaller(options) {
447
153
  const baseFetch = options.fetch ?? globalThis.fetch;
@@ -461,8 +167,11 @@ function createCaller(options) {
461
167
  }
462
168
  headers.set("accept", "application/json");
463
169
  if (spec.body !== void 0) headers.set("content-type", "application/json");
170
+ const key = spec.method === "POST" ? spec.options?.idempotencyKey ?? headers.get("idempotency-key") ?? crypto.randomUUID() : void 0;
171
+ if (key !== void 0) headers.set("idempotency-key", key);
172
+ const hasApiKey = headers.has("authorization");
464
173
  const url = withQuery(`${baseUrl}${spec.path}`, spec.query);
465
- return send(
174
+ return send2(
466
175
  baseFetch,
467
176
  url,
468
177
  (signal) => ({
@@ -472,35 +181,75 @@ function createCaller(options) {
472
181
  signal
473
182
  }),
474
183
  spec.options?.signal,
475
- retry
184
+ spec.method === "DELETE" ? { ...retry, maxRetries: 0 } : retry,
185
+ {
186
+ key: hasApiKey ? key : void 0,
187
+ hasApiKey,
188
+ replayable: key === void 0 || !hasApiKey || answerIsKept(spec.path, parseJson(JSON.stringify(spec.body ?? null)))
189
+ }
476
190
  );
477
191
  };
478
192
  }
479
- async function send(baseFetch, url, init, signal, retry) {
193
+ function answerIsKept(path, body) {
194
+ if (JOB_STARTS.has(path) || !isRecord(body)) return true;
195
+ return ![body, body.scrapeOptions, body.options].some(
196
+ (part) => isRecord(part) && part.zeroDataRetention === true
197
+ );
198
+ }
199
+ var NEVER_SENT = /* @__PURE__ */ new Set([
200
+ "ECONNREFUSED",
201
+ "ENOTFOUND",
202
+ "EAI_AGAIN",
203
+ "ENETUNREACH",
204
+ "EHOSTUNREACH",
205
+ "UND_ERR_CONNECT_TIMEOUT"
206
+ ]);
207
+ var requestMayHaveLeft = (error) => !NEVER_SENT.has(error.code ?? error.cause?.code ?? "");
208
+ var SEND_AGAIN = "Check before you send it again as a new call, or send it again with the same Idempotency-Key in details.idempotencyKey.";
209
+ function mayStillComplete(error, key) {
210
+ return new StophyError(`${error.message} An earlier send may still complete. ${SEND_AGAIN}`, {
211
+ status: error.status,
212
+ code: error.code,
213
+ retryable: error.retryable,
214
+ retryAfterSeconds: error.retryAfterSeconds,
215
+ requestId: error.requestId,
216
+ details: { ...error.details, idempotencyKey: key }
217
+ });
218
+ }
219
+ async function send2(baseFetch, url, init, signal, retry, plan) {
220
+ let earlierSendLost = false;
221
+ const mayHaveRun = (error) => error.status >= 500 && error.code !== "busy";
222
+ const failWith = (error) => plan.key !== void 0 && earlierSendLost && mayHaveRun(error) ? mayStillComplete(error, plan.key) : error;
480
223
  for (let n = 0; ; n += 1) {
481
224
  const deadline = withDeadline(signal, retry.timeoutMs);
482
225
  let waitMs;
483
226
  try {
484
227
  const response = await baseFetch(url, init(deadline.signal)).catch((error) => {
485
- if (deadline.signal.aborted || n >= retry.maxRetries) throw error;
228
+ if (signal?.aborted) throw error;
229
+ const mayHaveLeft = requestMayHaveLeft(error);
230
+ if (mayHaveLeft && !plan.replayable) throw Object.assign(error, { outcomeUnknown: true });
231
+ if (error.name === "TimeoutError" && !plan.hasApiKey) throw error;
232
+ if (n >= retry.maxRetries) {
233
+ throw (mayHaveLeft || earlierSendLost) && plan.key !== void 0 ? Object.assign(error, { idempotencyKey: plan.key }) : error;
234
+ }
235
+ earlierSendLost ||= mayHaveLeft;
486
236
  return void 0;
487
237
  });
488
238
  if (response === void 0) {
489
239
  waitMs = backoffMs(n, retry.initialDelayMs);
490
- } else if (n < retry.maxRetries && RETRYABLE_STATUS.has(response.status)) {
240
+ } else if (response.ok) {
241
+ return await readBody(response);
242
+ } else {
491
243
  const error = await errorFrom(response);
492
244
  const seconds = error.retryAfterSeconds;
493
- if (seconds !== void 0 && seconds > MAX_RETRY_WAIT_SECONDS) {
494
- throw error;
495
- }
245
+ if (!error.retryable || n >= retry.maxRetries) throw failWith(error);
246
+ if (seconds !== void 0 && seconds > MAX_RETRY_WAIT_SECONDS) throw failWith(error);
496
247
  waitMs = seconds === void 0 ? backoffMs(n, retry.initialDelayMs) : seconds * 1e3;
497
- } else {
498
- return await readBody(response);
499
248
  }
500
249
  } finally {
501
250
  deadline.clear();
502
251
  }
503
- await sleep(waitMs);
252
+ await sleep(waitMs, signal);
504
253
  }
505
254
  }
506
255
  function withDeadline(signal, timeoutMs) {
@@ -523,7 +272,6 @@ function withDeadline(signal, timeoutMs) {
523
272
  };
524
273
  }
525
274
  async function readBody(response) {
526
- if (!response.ok) throw await errorFrom(response);
527
275
  const text = await response.text();
528
276
  if (!text) {
529
277
  throw failed(response, "Stophy returned an empty response", {});
@@ -537,12 +285,12 @@ async function readBody(response) {
537
285
  async function errorFrom(response) {
538
286
  const text = await response.text();
539
287
  const error = readError(text ? parseJson(text) : null);
540
- const retryAfterSeconds = error.retryAfterSeconds ?? headerRetryAfter(response);
541
288
  return failed(response, error.message ?? `Stophy request failed with status ${response.status}`, {
542
289
  code: error.code,
543
290
  retryable: error.retryable ?? RETRYABLE_STATUS.has(response.status),
544
- retryAfterSeconds,
545
- requestId: error.requestId ?? headerRequestId(response)
291
+ retryAfterSeconds: error.retryAfterSeconds ?? headerRetryAfter(response),
292
+ requestId: headerRequestId(response) ?? error.requestId,
293
+ details: error.details
546
294
  });
547
295
  }
548
296
  function failed(response, message, options) {
@@ -551,7 +299,8 @@ function failed(response, message, options) {
551
299
  code: options.code,
552
300
  retryable: options.retryable ?? false,
553
301
  retryAfterSeconds: options.retryAfterSeconds,
554
- requestId: options.requestId ?? headerRequestId(response)
302
+ requestId: options.requestId ?? headerRequestId(response),
303
+ details: options.details
555
304
  });
556
305
  }
557
306
  function parseJson(text) {
@@ -561,15 +310,27 @@ function parseJson(text) {
561
310
  return null;
562
311
  }
563
312
  }
313
+ var ENVELOPE_FIELDS = /* @__PURE__ */ new Set([
314
+ "success",
315
+ "error",
316
+ "message",
317
+ "code",
318
+ "retryable",
319
+ "retryAfterSeconds",
320
+ "requestId"
321
+ ]);
564
322
  function readError(body) {
565
- if (!isRecord(body) || !isRecord(body.error)) return {};
566
- const error = body.error;
323
+ if (!isRecord(body)) return {};
324
+ const fields = isRecord(body.error) ? body.error : body;
567
325
  return {
568
- code: isString(error.code) ? error.code : void 0,
569
- message: isString(error.message) ? error.message : void 0,
570
- retryable: isBoolean(error.retryable) ? error.retryable : void 0,
571
- retryAfterSeconds: isNumber(error.retryAfterSeconds) ? error.retryAfterSeconds : void 0,
572
- requestId: isString(error.requestId) ? error.requestId : void 0
326
+ code: isString(fields.code) ? fields.code : void 0,
327
+ message: isString(fields.error) ? fields.error : isString(fields.message) ? fields.message : void 0,
328
+ retryable: isBoolean(fields.retryable) ? fields.retryable : void 0,
329
+ retryAfterSeconds: isNumber(fields.retryAfterSeconds) ? fields.retryAfterSeconds : void 0,
330
+ requestId: isString(fields.requestId) ? fields.requestId : void 0,
331
+ details: Object.fromEntries(
332
+ Object.entries(fields).filter(([key]) => !ENVELOPE_FIELDS.has(key))
333
+ )
573
334
  };
574
335
  }
575
336
  function headerRequestId(response) {
@@ -597,8 +358,19 @@ function backoffMs(attempt, base) {
597
358
  const window = base * 2 ** attempt;
598
359
  return window / 2 + Math.random() * (window / 2);
599
360
  }
600
- function sleep(ms) {
601
- return new Promise((resolve) => setTimeout(resolve, ms));
361
+ function sleep(ms, signal) {
362
+ return new Promise((resolve, reject) => {
363
+ if (signal?.aborted) return reject(signal.reason);
364
+ const onAbort = () => {
365
+ clearTimeout(timer);
366
+ reject(signal?.reason);
367
+ };
368
+ const timer = setTimeout(() => {
369
+ signal?.removeEventListener("abort", onAbort);
370
+ resolve();
371
+ }, ms);
372
+ signal?.addEventListener("abort", onAbort, { once: true });
373
+ });
602
374
  }
603
375
 
604
376
  // src/client.ts
@@ -606,7 +378,6 @@ function env(name) {
606
378
  return globalThis.process?.env[name];
607
379
  }
608
380
  var Stophy = class extends Surface {
609
- #call;
610
381
  constructor(input = {}) {
611
382
  const options = input instanceof Object ? input : { apiKey: input };
612
383
  const apiKey = options.apiKey?.trim() || env("STOPHY_API_KEY")?.trim();
@@ -616,13 +387,9 @@ var Stophy = class extends Surface {
616
387
  baseUrl: options.baseUrl ?? env("STOPHY_BASE_URL")
617
388
  });
618
389
  super(call);
619
- this.#call = call;
620
- }
621
- usage() {
622
- return usage(this.#call);
623
390
  }
624
- logs(query) {
625
- return logs(this.#call, query);
391
+ parsed(parser, url, options, request) {
392
+ return this.scrape({ url, formats: [{ type: "json", parser, options }] }, request);
626
393
  }
627
394
  };
628
395