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