stripe-loaders-core 0.1.0 → 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.
- package/LICENSE +21 -0
- package/README.md +31 -2
- package/dist/index.cjs +313 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +168 -0
- package/dist/index.d.ts +90 -8
- package/dist/index.js +275 -0
- package/dist/index.js.map +1 -0
- package/package.json +26 -17
- package/dist/index.d.ts.map +0 -1
- package/dist/index.spec.d.ts +0 -2
- package/dist/index.spec.d.ts.map +0 -1
- package/dist/stripe-loaders-core.cjs +0 -2
- package/dist/stripe-loaders-core.cjs.map +0 -1
- package/dist/stripe-loaders-core.js +0 -133
- package/dist/stripe-loaders-core.js.map +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 wpkyoto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -122,11 +122,14 @@ The main class for processing sitemaps.
|
|
|
122
122
|
#### Constructor
|
|
123
123
|
|
|
124
124
|
```typescript
|
|
125
|
-
constructor(options:
|
|
125
|
+
constructor(options: SitemapProcessorOptions = {})
|
|
126
126
|
```
|
|
127
127
|
|
|
128
128
|
- `options.debug`: Enable debug mode (default: false)
|
|
129
|
-
- `options.logger`: Custom logger implementation (default: ConsoleLogger)
|
|
129
|
+
- `options.logger`: Custom logger implementation (default: ConsoleLogger, which prints `log` / `warn` only in debug mode)
|
|
130
|
+
- `options.rateLimit`: Rate limiting and retry settings (see below)
|
|
131
|
+
- `options.fetch`: Custom fetch implementation (default: global `fetch`)
|
|
132
|
+
- `options.sleep`: Custom sleep implementation, mainly for tests
|
|
130
133
|
|
|
131
134
|
#### Methods
|
|
132
135
|
|
|
@@ -150,6 +153,32 @@ constructor(options: { debug?: boolean; logger?: Logger } = {})
|
|
|
150
153
|
- `fetchAndProcessSitemapIndex(indexUrl: string, baseUrl?: string): Promise<string[]>`
|
|
151
154
|
- Fetch a sitemap index and process all referenced sitemaps
|
|
152
155
|
|
|
156
|
+
### Rate limiting and retries
|
|
157
|
+
|
|
158
|
+
Sitemap requests (and the loaders in `langchain-stripe-loader`) are sent one at a time.
|
|
159
|
+
`fetchAndProcessSitemapIndex` waits between partitions, and every request retries HTTP 429 / 5xx
|
|
160
|
+
responses and network errors with exponential backoff, honouring `Retry-After`.
|
|
161
|
+
|
|
162
|
+
| Option | Default | Meaning |
|
|
163
|
+
| ----------------- | ------- | ------------------------------------------------------- |
|
|
164
|
+
| `requestDelayMs` | 1000 | Delay between requests |
|
|
165
|
+
| `requestJitterMs` | 500 | Random variation (±half of this value) |
|
|
166
|
+
| `maxRetries` | 3 | Retries after the first attempt |
|
|
167
|
+
| `backoffBaseMs` | 1000 | Exponential backoff base |
|
|
168
|
+
| `backoffMaxMs` | 30000 | Upper bound for a single wait (also caps `Retry-After`) |
|
|
169
|
+
|
|
170
|
+
The helpers are exported for reuse:
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
import { fetchWithRetry, RequestPacer, resolveRateLimit } from 'stripe-loaders-core';
|
|
174
|
+
|
|
175
|
+
const pacer = new RequestPacer(resolveRateLimit({ requestDelayMs: 2000 }));
|
|
176
|
+
for (const url of urls) {
|
|
177
|
+
await pacer.wait(); // no wait before the first request
|
|
178
|
+
const response = await fetchWithRetry(url); // returns the final response, including 4xx
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
153
182
|
### Logger Interface
|
|
154
183
|
|
|
155
184
|
Interface for custom loggers.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
ConsoleLogger: () => ConsoleLogger,
|
|
24
|
+
DEFAULT_RATE_LIMIT: () => DEFAULT_RATE_LIMIT,
|
|
25
|
+
RequestPacer: () => RequestPacer,
|
|
26
|
+
SitemapProcessor: () => SitemapProcessor,
|
|
27
|
+
calculateExponentialBackoff: () => calculateExponentialBackoff,
|
|
28
|
+
delay: () => delay,
|
|
29
|
+
delayWithJitter: () => delayWithJitter,
|
|
30
|
+
escapeRegExp: () => escapeRegExp,
|
|
31
|
+
fetchWithRetry: () => fetchWithRetry,
|
|
32
|
+
parseRetryAfter: () => parseRetryAfter,
|
|
33
|
+
resolveRateLimit: () => resolveRateLimit,
|
|
34
|
+
withJitter: () => withJitter
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
|
|
38
|
+
// src/http.ts
|
|
39
|
+
var DEFAULT_RATE_LIMIT = Object.freeze({
|
|
40
|
+
requestDelayMs: 1e3,
|
|
41
|
+
requestJitterMs: 500,
|
|
42
|
+
maxRetries: 3,
|
|
43
|
+
backoffBaseMs: 1e3,
|
|
44
|
+
backoffMaxMs: 3e4
|
|
45
|
+
});
|
|
46
|
+
function resolveRateLimit(options) {
|
|
47
|
+
return { ...DEFAULT_RATE_LIMIT, ...options };
|
|
48
|
+
}
|
|
49
|
+
function delay(ms) {
|
|
50
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
51
|
+
}
|
|
52
|
+
function withJitter(baseMs, jitterMs, random = Math.random) {
|
|
53
|
+
const jitter = random() * jitterMs - jitterMs / 2;
|
|
54
|
+
return Math.max(0, Math.floor(baseMs + jitter));
|
|
55
|
+
}
|
|
56
|
+
async function delayWithJitter(baseMs, jitterMs, sleep = delay) {
|
|
57
|
+
const ms = withJitter(baseMs, jitterMs);
|
|
58
|
+
if (ms > 0) {
|
|
59
|
+
await sleep(ms);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function calculateExponentialBackoff(attempt, baseMs, maxMs) {
|
|
63
|
+
return Math.min(baseMs * Math.pow(2, attempt), maxMs);
|
|
64
|
+
}
|
|
65
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
66
|
+
if (!value) {
|
|
67
|
+
return void 0;
|
|
68
|
+
}
|
|
69
|
+
const trimmed = value.trim();
|
|
70
|
+
if (/^\d+$/.test(trimmed)) {
|
|
71
|
+
const ms2 = Number(trimmed) * 1e3;
|
|
72
|
+
return ms2 > 0 ? ms2 : void 0;
|
|
73
|
+
}
|
|
74
|
+
const date = Date.parse(trimmed);
|
|
75
|
+
if (Number.isNaN(date)) {
|
|
76
|
+
return void 0;
|
|
77
|
+
}
|
|
78
|
+
const ms = date - now;
|
|
79
|
+
return ms > 0 ? ms : void 0;
|
|
80
|
+
}
|
|
81
|
+
function isRetryableStatus(status) {
|
|
82
|
+
return status === 429 || status >= 500;
|
|
83
|
+
}
|
|
84
|
+
async function fetchWithRetry(url, init, options = {}) {
|
|
85
|
+
const limits = resolveRateLimit(options.rateLimit);
|
|
86
|
+
const doFetch = options.fetch ?? ((input, reqInit) => fetch(input, reqInit));
|
|
87
|
+
const sleep = options.sleep ?? delay;
|
|
88
|
+
for (let attempt = 0; ; attempt++) {
|
|
89
|
+
let response;
|
|
90
|
+
try {
|
|
91
|
+
response = await doFetch(url, init);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (attempt >= limits.maxRetries) {
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
const waitMs2 = calculateExponentialBackoff(
|
|
97
|
+
attempt,
|
|
98
|
+
limits.backoffBaseMs,
|
|
99
|
+
limits.backoffMaxMs
|
|
100
|
+
);
|
|
101
|
+
options.onRetry?.({ url, attempt: attempt + 1, waitMs: waitMs2, reason: String(error) });
|
|
102
|
+
await delayWithJitter(waitMs2, limits.requestJitterMs, sleep);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (!isRetryableStatus(response.status) || attempt >= limits.maxRetries) {
|
|
106
|
+
return response;
|
|
107
|
+
}
|
|
108
|
+
const retryAfter = parseRetryAfter(response.headers?.get?.("Retry-After"));
|
|
109
|
+
const waitMs = Math.min(
|
|
110
|
+
retryAfter ?? calculateExponentialBackoff(attempt, limits.backoffBaseMs, limits.backoffMaxMs),
|
|
111
|
+
limits.backoffMaxMs
|
|
112
|
+
);
|
|
113
|
+
options.onRetry?.({ url, attempt: attempt + 1, waitMs, reason: `HTTP ${response.status}` });
|
|
114
|
+
await delayWithJitter(waitMs, limits.requestJitterMs, sleep);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
var RequestPacer = class {
|
|
118
|
+
constructor(limits, sleep = delay) {
|
|
119
|
+
this.limits = limits;
|
|
120
|
+
this.sleep = sleep;
|
|
121
|
+
this.started = false;
|
|
122
|
+
}
|
|
123
|
+
async wait() {
|
|
124
|
+
if (this.started) {
|
|
125
|
+
await delayWithJitter(this.limits.requestDelayMs, this.limits.requestJitterMs, this.sleep);
|
|
126
|
+
}
|
|
127
|
+
this.started = true;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// src/index.ts
|
|
132
|
+
function escapeRegExp(value) {
|
|
133
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
134
|
+
}
|
|
135
|
+
var ConsoleLogger = class {
|
|
136
|
+
constructor(debug = false) {
|
|
137
|
+
this.debug = debug;
|
|
138
|
+
}
|
|
139
|
+
log(message) {
|
|
140
|
+
if (this.debug) {
|
|
141
|
+
console.log(message);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
error(message) {
|
|
145
|
+
console.error(message);
|
|
146
|
+
}
|
|
147
|
+
warn(message) {
|
|
148
|
+
if (this.debug) {
|
|
149
|
+
console.warn(message);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
var SitemapProcessor = class {
|
|
154
|
+
/**
|
|
155
|
+
* Constructor for SitemapProcessor
|
|
156
|
+
* @param options Configuration options
|
|
157
|
+
*/
|
|
158
|
+
constructor(options = {}) {
|
|
159
|
+
this.debug = options.debug ?? false;
|
|
160
|
+
this.logger = options.logger ?? new ConsoleLogger(this.debug);
|
|
161
|
+
this.rateLimit = resolveRateLimit(options.rateLimit);
|
|
162
|
+
this.fetchImpl = options.fetch;
|
|
163
|
+
this.sleep = options.sleep;
|
|
164
|
+
}
|
|
165
|
+
fetchUrl(url) {
|
|
166
|
+
return fetchWithRetry(url, void 0, {
|
|
167
|
+
rateLimit: this.rateLimit,
|
|
168
|
+
fetch: this.fetchImpl,
|
|
169
|
+
sleep: this.sleep,
|
|
170
|
+
onRetry: ({ attempt, waitMs, reason }) => this.logWarning(`Retrying ${url} (attempt ${attempt}, ${reason}) in ${waitMs}ms`)
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Log a message if debug mode is enabled
|
|
175
|
+
* @param message Message to log
|
|
176
|
+
*/
|
|
177
|
+
log(message) {
|
|
178
|
+
this.logger.log(message);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Log an error message
|
|
182
|
+
* @param message Error message to log
|
|
183
|
+
*/
|
|
184
|
+
logError(message) {
|
|
185
|
+
this.logger.error(message);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Log a warning message
|
|
189
|
+
* @param message Warning message to log
|
|
190
|
+
*/
|
|
191
|
+
logWarning(message) {
|
|
192
|
+
this.logger.warn(message);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Extract URLs from a sitemap
|
|
196
|
+
* @param content Sitemap XML content
|
|
197
|
+
* @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)
|
|
198
|
+
* @returns Array of extracted URLs
|
|
199
|
+
*/
|
|
200
|
+
extractUrlsFromSitemap(content, baseUrl = "https://docs.stripe.com/") {
|
|
201
|
+
const urlRegex = new RegExp(`<loc>(${escapeRegExp(baseUrl)}[^<]+)</loc>`, "g");
|
|
202
|
+
const urls = [];
|
|
203
|
+
let match;
|
|
204
|
+
while ((match = urlRegex.exec(content)) !== null) {
|
|
205
|
+
urls.push(match[1]);
|
|
206
|
+
}
|
|
207
|
+
return urls;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Extract sitemap URLs from a sitemap index
|
|
211
|
+
* @param content Sitemap index XML content
|
|
212
|
+
* @returns Array of extracted sitemap URLs
|
|
213
|
+
*/
|
|
214
|
+
extractSitemapUrlsFromIndex(content) {
|
|
215
|
+
if (!content || typeof content !== "string") {
|
|
216
|
+
this.logError("Invalid input: content must be a string");
|
|
217
|
+
return [];
|
|
218
|
+
}
|
|
219
|
+
if (!content.includes("<?xml") || !content.includes("<sitemapindex")) {
|
|
220
|
+
this.logError("Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements.");
|
|
221
|
+
return [];
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
const sitemapRegex = /<loc>([^<]+)<\/loc>/g;
|
|
225
|
+
const sitemapUrls = [];
|
|
226
|
+
let match;
|
|
227
|
+
while ((match = sitemapRegex.exec(content)) !== null) {
|
|
228
|
+
const url = match[1];
|
|
229
|
+
try {
|
|
230
|
+
new URL(url);
|
|
231
|
+
sitemapUrls.push(url);
|
|
232
|
+
} catch (urlError) {
|
|
233
|
+
this.logWarning(`Skipped invalid URL format: ${url}`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (sitemapUrls.length === 0) {
|
|
237
|
+
this.logWarning("No valid URLs found in sitemap index");
|
|
238
|
+
}
|
|
239
|
+
return sitemapUrls;
|
|
240
|
+
} catch (error) {
|
|
241
|
+
this.logError(`Error extracting URLs from sitemap index: ${error}`);
|
|
242
|
+
return [];
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Find newly added URLs
|
|
247
|
+
* @param currentUrls Current URL list
|
|
248
|
+
* @param previousUrls Previous URL list
|
|
249
|
+
* @returns Array of newly added URLs
|
|
250
|
+
*/
|
|
251
|
+
findNewUrls(currentUrls, previousUrls) {
|
|
252
|
+
const previousUrlSet = new Set(previousUrls);
|
|
253
|
+
return currentUrls.filter((url) => !previousUrlSet.has(url));
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Fetch and process a sitemap
|
|
257
|
+
* @param url Sitemap URL
|
|
258
|
+
* @param baseUrl Base URL part to extract
|
|
259
|
+
* @returns List of retrieved URLs
|
|
260
|
+
*/
|
|
261
|
+
async fetchAndProcessSitemap(url, baseUrl) {
|
|
262
|
+
const response = await this.fetchUrl(url);
|
|
263
|
+
if (!response.ok) {
|
|
264
|
+
throw new Error(`Failed to fetch sitemap: ${response.status} ${response.statusText}`);
|
|
265
|
+
}
|
|
266
|
+
const sitemapContent = await response.text();
|
|
267
|
+
return this.extractUrlsFromSitemap(sitemapContent, baseUrl);
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Fetch and process a sitemap index
|
|
271
|
+
* @param indexUrl Sitemap index URL
|
|
272
|
+
* @param baseUrl Base URL part to extract
|
|
273
|
+
* @returns List of retrieved URLs
|
|
274
|
+
*/
|
|
275
|
+
async fetchAndProcessSitemapIndex(indexUrl, baseUrl) {
|
|
276
|
+
this.log(`Fetching sitemap index: ${indexUrl}`);
|
|
277
|
+
const pacer = new RequestPacer(this.rateLimit, this.sleep);
|
|
278
|
+
await pacer.wait();
|
|
279
|
+
const response = await this.fetchUrl(indexUrl);
|
|
280
|
+
if (!response.ok) {
|
|
281
|
+
throw new Error(`Failed to fetch sitemap index: ${response.status} ${response.statusText}`);
|
|
282
|
+
}
|
|
283
|
+
const indexContent = await response.text();
|
|
284
|
+
const sitemapUrls = this.extractSitemapUrlsFromIndex(indexContent);
|
|
285
|
+
this.log(`Number of sitemap partitions: ${sitemapUrls.length}`);
|
|
286
|
+
const allUrls = [];
|
|
287
|
+
for (let i = 0; i < sitemapUrls.length; i++) {
|
|
288
|
+
const sitemapUrl = sitemapUrls[i];
|
|
289
|
+
this.log(`Processing partition ${i + 1}/${sitemapUrls.length}: ${sitemapUrl}`);
|
|
290
|
+
await pacer.wait();
|
|
291
|
+
const urls = await this.fetchAndProcessSitemap(sitemapUrl, baseUrl);
|
|
292
|
+
this.log(`Retrieved ${urls.length} URLs from partition ${i + 1}`);
|
|
293
|
+
allUrls.push(...urls);
|
|
294
|
+
}
|
|
295
|
+
return allUrls;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
299
|
+
0 && (module.exports = {
|
|
300
|
+
ConsoleLogger,
|
|
301
|
+
DEFAULT_RATE_LIMIT,
|
|
302
|
+
RequestPacer,
|
|
303
|
+
SitemapProcessor,
|
|
304
|
+
calculateExponentialBackoff,
|
|
305
|
+
delay,
|
|
306
|
+
delayWithJitter,
|
|
307
|
+
escapeRegExp,
|
|
308
|
+
fetchWithRetry,
|
|
309
|
+
parseRetryAfter,
|
|
310
|
+
resolveRateLimit,
|
|
311
|
+
withJitter
|
|
312
|
+
});
|
|
313
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/http.ts"],"sourcesContent":["/**\n * Utility functions for processing Stripe docs sitemaps\n */\n\nimport {\n fetchWithRetry,\n resolveRateLimit,\n RequestPacer,\n type FetchLike,\n type RateLimitOptions,\n type SleepFn,\n} from './http';\n\nexport * from './http';\n\n/**\n * Escape a string so it can be embedded in a regular expression literally.\n */\nexport function escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport interface SitemapProcessorOptions {\n debug?: boolean;\n logger?: Logger;\n /** Rate limiting and retry settings for sitemap requests. */\n rateLimit?: Partial<RateLimitOptions>;\n /** Custom fetch implementation (defaults to the global fetch). */\n fetch?: FetchLike;\n /** Custom sleep implementation, mainly for tests. */\n sleep?: SleepFn;\n}\n\n/**\n * Logger interface for SitemapProcessor\n */\nexport interface Logger {\n log(message: string): void;\n error(message: string): void;\n warn(message: string): void;\n}\n\n/**\n * Default console logger implementation\n */\nexport class ConsoleLogger implements Logger {\n constructor(private debug: boolean = false) {}\n\n log(message: string): void {\n if (this.debug) {\n console.log(message);\n }\n }\n\n error(message: string): void {\n console.error(message);\n }\n\n warn(message: string): void {\n if (this.debug) {\n console.warn(message);\n }\n }\n}\n\n/**\n * Utility class for processing Stripe docs sitemaps\n */\nexport class SitemapProcessor {\n private debug: boolean;\n private logger: Logger;\n private rateLimit: RateLimitOptions;\n private fetchImpl?: FetchLike;\n private sleep?: SleepFn;\n\n /**\n * Constructor for SitemapProcessor\n * @param options Configuration options\n */\n constructor(options: SitemapProcessorOptions = {}) {\n this.debug = options.debug ?? false;\n this.logger = options.logger ?? new ConsoleLogger(this.debug);\n this.rateLimit = resolveRateLimit(options.rateLimit);\n this.fetchImpl = options.fetch;\n this.sleep = options.sleep;\n }\n\n private fetchUrl(url: string): Promise<Response> {\n return fetchWithRetry(url, undefined, {\n rateLimit: this.rateLimit,\n fetch: this.fetchImpl,\n sleep: this.sleep,\n onRetry: ({ attempt, waitMs, reason }) =>\n this.logWarning(`Retrying ${url} (attempt ${attempt}, ${reason}) in ${waitMs}ms`),\n });\n }\n\n /**\n * Log a message if debug mode is enabled\n * @param message Message to log\n */\n private log(message: string): void {\n this.logger.log(message);\n }\n\n /**\n * Log an error message\n * @param message Error message to log\n */\n private logError(message: string): void {\n this.logger.error(message);\n }\n\n /**\n * Log a warning message\n * @param message Warning message to log\n */\n private logWarning(message: string): void {\n this.logger.warn(message);\n }\n\n /**\n * Extract URLs from a sitemap\n * @param content Sitemap XML content\n * @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)\n * @returns Array of extracted URLs\n */\n public extractUrlsFromSitemap(\n content: string,\n baseUrl: string = 'https://docs.stripe.com/'\n ): string[] {\n const urlRegex = new RegExp(`<loc>(${escapeRegExp(baseUrl)}[^<]+)<\\/loc>`, 'g');\n const urls: string[] = [];\n let match;\n\n while ((match = urlRegex.exec(content)) !== null) {\n urls.push(match[1]);\n }\n\n return urls;\n }\n\n /**\n * Extract sitemap URLs from a sitemap index\n * @param content Sitemap index XML content\n * @returns Array of extracted sitemap URLs\n */\n public extractSitemapUrlsFromIndex(content: string): string[] {\n // Input validation\n if (!content || typeof content !== 'string') {\n this.logError('Invalid input: content must be a string');\n return [];\n }\n\n // Basic XML structure validation\n if (!content.includes('<?xml') || !content.includes('<sitemapindex')) {\n this.logError('Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements.');\n return [];\n }\n\n try {\n const sitemapRegex = /<loc>([^<]+)<\\/loc>/g;\n const sitemapUrls: string[] = [];\n let match;\n\n while ((match = sitemapRegex.exec(content)) !== null) {\n // URL validation (optional)\n const url = match[1];\n try {\n new URL(url); // Check if URL is valid\n sitemapUrls.push(url);\n } catch (urlError) {\n this.logWarning(`Skipped invalid URL format: ${url}`);\n // Skip invalid URLs\n }\n }\n\n if (sitemapUrls.length === 0) {\n this.logWarning('No valid URLs found in sitemap index');\n }\n\n return sitemapUrls;\n } catch (error) {\n this.logError(`Error extracting URLs from sitemap index: ${error}`);\n return []; // Return empty array on error\n }\n }\n\n /**\n * Find newly added URLs\n * @param currentUrls Current URL list\n * @param previousUrls Previous URL list\n * @returns Array of newly added URLs\n */\n public findNewUrls(currentUrls: string[], previousUrls: string[]): string[] {\n const previousUrlSet = new Set(previousUrls);\n return currentUrls.filter(url => !previousUrlSet.has(url));\n }\n\n /**\n * Fetch and process a sitemap\n * @param url Sitemap URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemap(url: string, baseUrl?: string): Promise<string[]> {\n const response = await this.fetchUrl(url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap: ${response.status} ${response.statusText}`);\n }\n\n const sitemapContent = await response.text();\n return this.extractUrlsFromSitemap(sitemapContent, baseUrl);\n }\n\n /**\n * Fetch and process a sitemap index\n * @param indexUrl Sitemap index URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemapIndex(indexUrl: string, baseUrl?: string): Promise<string[]> {\n this.log(`Fetching sitemap index: ${indexUrl}`);\n const pacer = new RequestPacer(this.rateLimit, this.sleep);\n await pacer.wait();\n const response = await this.fetchUrl(indexUrl);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap index: ${response.status} ${response.statusText}`);\n }\n\n const indexContent = await response.text();\n const sitemapUrls = this.extractSitemapUrlsFromIndex(indexContent);\n this.log(`Number of sitemap partitions: ${sitemapUrls.length}`);\n\n // Combine URLs from each sitemap file\n const allUrls: string[] = [];\n\n for (let i = 0; i < sitemapUrls.length; i++) {\n const sitemapUrl = sitemapUrls[i];\n this.log(`Processing partition ${i + 1}/${sitemapUrls.length}: ${sitemapUrl}`);\n await pacer.wait();\n const urls = await this.fetchAndProcessSitemap(sitemapUrl, baseUrl);\n this.log(`Retrieved ${urls.length} URLs from partition ${i + 1}`);\n allUrls.push(...urls);\n }\n\n return allUrls;\n }\n}\n","/**\n * Rate limiting and retry helpers for fetching Stripe sites.\n *\n * Requests are sent one at a time with a delay between them, and HTTP 429 / 5xx\n * responses are retried with exponential backoff (honouring `Retry-After`).\n * The defaults follow the conservative access policy used by\n * hideokamoto/stripe-docs-updates for docs.stripe.com and stripe.com.\n */\n\nexport interface RateLimitOptions {\n /** Delay between consecutive requests in milliseconds. */\n requestDelayMs: number;\n /** Random variation (±half of this value) added to each delay in milliseconds. */\n requestJitterMs: number;\n /** Number of retries after the first attempt for 429 / 5xx responses and network errors. */\n maxRetries: number;\n /** Base delay for exponential backoff in milliseconds. */\n backoffBaseMs: number;\n /** Upper bound for a single backoff delay in milliseconds. */\n backoffMaxMs: number;\n}\n\nexport const DEFAULT_RATE_LIMIT: Readonly<RateLimitOptions> = Object.freeze({\n requestDelayMs: 1000,\n requestJitterMs: 500,\n maxRetries: 3,\n backoffBaseMs: 1000,\n backoffMaxMs: 30000,\n});\n\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\nexport type SleepFn = (ms: number) => Promise<void>;\n\nexport function resolveRateLimit(options?: Partial<RateLimitOptions>): RateLimitOptions {\n return { ...DEFAULT_RATE_LIMIT, ...options };\n}\n\nexport function delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport function withJitter(baseMs: number, jitterMs: number, random: () => number = Math.random) {\n const jitter = random() * jitterMs - jitterMs / 2;\n return Math.max(0, Math.floor(baseMs + jitter));\n}\n\nexport async function delayWithJitter(\n baseMs: number,\n jitterMs: number,\n sleep: SleepFn = delay\n): Promise<void> {\n const ms = withJitter(baseMs, jitterMs);\n if (ms > 0) {\n await sleep(ms);\n }\n}\n\nexport function calculateExponentialBackoff(attempt: number, baseMs: number, maxMs: number) {\n return Math.min(baseMs * Math.pow(2, attempt), maxMs);\n}\n\n/**\n * Parse a `Retry-After` header (seconds or HTTP date) into milliseconds.\n * Returns undefined when the header is missing, invalid, or not in the future.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number = Date.now()) {\n if (!value) {\n return undefined;\n }\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) {\n const ms = Number(trimmed) * 1000;\n return ms > 0 ? ms : undefined;\n }\n const date = Date.parse(trimmed);\n if (Number.isNaN(date)) {\n return undefined;\n }\n const ms = date - now;\n return ms > 0 ? ms : undefined;\n}\n\nfunction isRetryableStatus(status: number): boolean {\n return status === 429 || status >= 500;\n}\n\nexport interface FetchWithRetryOptions {\n rateLimit?: Partial<RateLimitOptions>;\n fetch?: FetchLike;\n sleep?: SleepFn;\n /** Called before each retry; useful for logging. */\n onRetry?: (info: { url: string; attempt: number; waitMs: number; reason: string }) => void;\n}\n\n/**\n * Fetch a URL, retrying 429 / 5xx responses and network errors.\n *\n * The final response is returned as-is, including non-2xx responses, so the\n * caller decides how to treat 404 and similar statuses. A network error is\n * rethrown after the last retry.\n */\nexport async function fetchWithRetry(\n url: string,\n init?: RequestInit,\n options: FetchWithRetryOptions = {}\n): Promise<Response> {\n const limits = resolveRateLimit(options.rateLimit);\n const doFetch: FetchLike = options.fetch ?? ((input, reqInit) => fetch(input, reqInit));\n const sleep = options.sleep ?? delay;\n\n for (let attempt = 0; ; attempt++) {\n let response: Response;\n try {\n response = await doFetch(url, init);\n } catch (error) {\n if (attempt >= limits.maxRetries) {\n throw error;\n }\n const waitMs = calculateExponentialBackoff(\n attempt,\n limits.backoffBaseMs,\n limits.backoffMaxMs\n );\n options.onRetry?.({ url, attempt: attempt + 1, waitMs, reason: String(error) });\n await delayWithJitter(waitMs, limits.requestJitterMs, sleep);\n continue;\n }\n\n if (!isRetryableStatus(response.status) || attempt >= limits.maxRetries) {\n return response;\n }\n\n const retryAfter = parseRetryAfter(response.headers?.get?.('Retry-After'));\n const waitMs = Math.min(\n retryAfter ?? calculateExponentialBackoff(attempt, limits.backoffBaseMs, limits.backoffMaxMs),\n limits.backoffMaxMs\n );\n options.onRetry?.({ url, attempt: attempt + 1, waitMs, reason: `HTTP ${response.status}` });\n await delayWithJitter(waitMs, limits.requestJitterMs, sleep);\n }\n}\n\n/**\n * Sequential request pacer: waits `requestDelayMs` (± jitter) before every\n * request except the first one.\n */\nexport class RequestPacer {\n private started = false;\n\n constructor(\n private readonly limits: RateLimitOptions,\n private readonly sleep: SleepFn = delay\n ) {}\n\n async wait(): Promise<void> {\n if (this.started) {\n await delayWithJitter(this.limits.requestDelayMs, this.limits.requestJitterMs, this.sleep);\n }\n this.started = true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBO,IAAM,qBAAiD,OAAO,OAAO;AAAA,EAC1E,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,cAAc;AAChB,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ching Stripe sites.
|
|
3
|
+
*
|
|
4
|
+
* Requests are sent one at a time with a delay between them, and HTTP 429 / 5xx
|
|
5
|
+
* responses are retried with exponential backoff (honouring `Retry-After`).
|
|
6
|
+
* The defaults follow the conservative access policy used by
|
|
7
|
+
* hideokamoto/stripe-docs-updates for docs.stripe.com and stripe.com.
|
|
8
|
+
*/
|
|
9
|
+
interface RateLimitOptions {
|
|
10
|
+
/** Delay between consecutive requests in milliseconds. */
|
|
11
|
+
requestDelayMs: number;
|
|
12
|
+
/** Random variation (±half of this value) added to each delay in milliseconds. */
|
|
13
|
+
requestJitterMs: number;
|
|
14
|
+
/** Number of retries after the first attempt for 429 / 5xx responses and network errors. */
|
|
15
|
+
maxRetries: number;
|
|
16
|
+
/** Base delay for exponential backoff in milliseconds. */
|
|
17
|
+
backoffBaseMs: number;
|
|
18
|
+
/** Upper bound for a single backoff delay in milliseconds. */
|
|
19
|
+
backoffMaxMs: number;
|
|
20
|
+
}
|
|
21
|
+
declare const DEFAULT_RATE_LIMIT: Readonly<RateLimitOptions>;
|
|
22
|
+
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
23
|
+
type SleepFn = (ms: number) => Promise<void>;
|
|
24
|
+
declare function resolveRateLimit(options?: Partial<RateLimitOptions>): RateLimitOptions;
|
|
25
|
+
declare function delay(ms: number): Promise<void>;
|
|
26
|
+
declare function withJitter(baseMs: number, jitterMs: number, random?: () => number): number;
|
|
27
|
+
declare function delayWithJitter(baseMs: number, jitterMs: number, sleep?: SleepFn): Promise<void>;
|
|
28
|
+
declare function calculateExponentialBackoff(attempt: number, baseMs: number, maxMs: number): number;
|
|
29
|
+
/**
|
|
30
|
+
* Parse a `Retry-After` header (seconds or HTTP date) into milliseconds.
|
|
31
|
+
* Returns undefined when the header is missing, invalid, or not in the future.
|
|
32
|
+
*/
|
|
33
|
+
declare function parseRetryAfter(value: string | null | undefined, now?: number): number | undefined;
|
|
34
|
+
interface FetchWithRetryOptions {
|
|
35
|
+
rateLimit?: Partial<RateLimitOptions>;
|
|
36
|
+
fetch?: FetchLike;
|
|
37
|
+
sleep?: SleepFn;
|
|
38
|
+
/** Called before each retry; useful for logging. */
|
|
39
|
+
onRetry?: (info: {
|
|
40
|
+
url: string;
|
|
41
|
+
attempt: number;
|
|
42
|
+
waitMs: number;
|
|
43
|
+
reason: string;
|
|
44
|
+
}) => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Fetch a URL, retrying 429 / 5xx responses and network errors.
|
|
48
|
+
*
|
|
49
|
+
* The final response is returned as-is, including non-2xx responses, so the
|
|
50
|
+
* caller decides how to treat 404 and similar statuses. A network error is
|
|
51
|
+
* rethrown after the last retry.
|
|
52
|
+
*/
|
|
53
|
+
declare function fetchWithRetry(url: string, init?: RequestInit, options?: FetchWithRetryOptions): Promise<Response>;
|
|
54
|
+
/**
|
|
55
|
+
* Sequential request pacer: waits `requestDelayMs` (± jitter) before every
|
|
56
|
+
* request except the first one.
|
|
57
|
+
*/
|
|
58
|
+
declare class RequestPacer {
|
|
59
|
+
private readonly limits;
|
|
60
|
+
private readonly sleep;
|
|
61
|
+
private started;
|
|
62
|
+
constructor(limits: RateLimitOptions, sleep?: SleepFn);
|
|
63
|
+
wait(): Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Utility functions for processing Stripe docs sitemaps
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Escape a string so it can be embedded in a regular expression literally.
|
|
72
|
+
*/
|
|
73
|
+
declare function escapeRegExp(value: string): string;
|
|
74
|
+
interface SitemapProcessorOptions {
|
|
75
|
+
debug?: boolean;
|
|
76
|
+
logger?: Logger;
|
|
77
|
+
/** Rate limiting and retry settings for sitemap requests. */
|
|
78
|
+
rateLimit?: Partial<RateLimitOptions>;
|
|
79
|
+
/** Custom fetch implementation (defaults to the global fetch). */
|
|
80
|
+
fetch?: FetchLike;
|
|
81
|
+
/** Custom sleep implementation, mainly for tests. */
|
|
82
|
+
sleep?: SleepFn;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Logger interface for SitemapProcessor
|
|
86
|
+
*/
|
|
87
|
+
interface Logger {
|
|
88
|
+
log(message: string): void;
|
|
89
|
+
error(message: string): void;
|
|
90
|
+
warn(message: string): void;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Default console logger implementation
|
|
94
|
+
*/
|
|
95
|
+
declare class ConsoleLogger implements Logger {
|
|
96
|
+
private debug;
|
|
97
|
+
constructor(debug?: boolean);
|
|
98
|
+
log(message: string): void;
|
|
99
|
+
error(message: string): void;
|
|
100
|
+
warn(message: string): void;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Utility class for processing Stripe docs sitemaps
|
|
104
|
+
*/
|
|
105
|
+
declare class SitemapProcessor {
|
|
106
|
+
private debug;
|
|
107
|
+
private logger;
|
|
108
|
+
private rateLimit;
|
|
109
|
+
private fetchImpl?;
|
|
110
|
+
private sleep?;
|
|
111
|
+
/**
|
|
112
|
+
* Constructor for SitemapProcessor
|
|
113
|
+
* @param options Configuration options
|
|
114
|
+
*/
|
|
115
|
+
constructor(options?: SitemapProcessorOptions);
|
|
116
|
+
private fetchUrl;
|
|
117
|
+
/**
|
|
118
|
+
* Log a message if debug mode is enabled
|
|
119
|
+
* @param message Message to log
|
|
120
|
+
*/
|
|
121
|
+
private log;
|
|
122
|
+
/**
|
|
123
|
+
* Log an error message
|
|
124
|
+
* @param message Error message to log
|
|
125
|
+
*/
|
|
126
|
+
private logError;
|
|
127
|
+
/**
|
|
128
|
+
* Log a warning message
|
|
129
|
+
* @param message Warning message to log
|
|
130
|
+
*/
|
|
131
|
+
private logWarning;
|
|
132
|
+
/**
|
|
133
|
+
* Extract URLs from a sitemap
|
|
134
|
+
* @param content Sitemap XML content
|
|
135
|
+
* @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)
|
|
136
|
+
* @returns Array of extracted URLs
|
|
137
|
+
*/
|
|
138
|
+
extractUrlsFromSitemap(content: string, baseUrl?: string): string[];
|
|
139
|
+
/**
|
|
140
|
+
* Extract sitemap URLs from a sitemap index
|
|
141
|
+
* @param content Sitemap index XML content
|
|
142
|
+
* @returns Array of extracted sitemap URLs
|
|
143
|
+
*/
|
|
144
|
+
extractSitemapUrlsFromIndex(content: string): string[];
|
|
145
|
+
/**
|
|
146
|
+
* Find newly added URLs
|
|
147
|
+
* @param currentUrls Current URL list
|
|
148
|
+
* @param previousUrls Previous URL list
|
|
149
|
+
* @returns Array of newly added URLs
|
|
150
|
+
*/
|
|
151
|
+
findNewUrls(currentUrls: string[], previousUrls: string[]): string[];
|
|
152
|
+
/**
|
|
153
|
+
* Fetch and process a sitemap
|
|
154
|
+
* @param url Sitemap URL
|
|
155
|
+
* @param baseUrl Base URL part to extract
|
|
156
|
+
* @returns List of retrieved URLs
|
|
157
|
+
*/
|
|
158
|
+
fetchAndProcessSitemap(url: string, baseUrl?: string): Promise<string[]>;
|
|
159
|
+
/**
|
|
160
|
+
* Fetch and process a sitemap index
|
|
161
|
+
* @param indexUrl Sitemap index URL
|
|
162
|
+
* @param baseUrl Base URL part to extract
|
|
163
|
+
* @returns List of retrieved URLs
|
|
164
|
+
*/
|
|
165
|
+
fetchAndProcessSitemapIndex(indexUrl: string, baseUrl?: string): Promise<string[]>;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export { ConsoleLogger, DEFAULT_RATE_LIMIT, type FetchLike, type FetchWithRetryOptions, type Logger, type RateLimitOptions, RequestPacer, SitemapProcessor, type SitemapProcessorOptions, type SleepFn, calculateExponentialBackoff, delay, delayWithJitter, escapeRegExp, fetchWithRetry, parseRetryAfter, resolveRateLimit, withJitter };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate limiting and retry helpers for fetching Stripe sites.
|
|
3
|
+
*
|
|
4
|
+
* Requests are sent one at a time with a delay between them, and HTTP 429 / 5xx
|
|
5
|
+
* responses are retried with exponential backoff (honouring `Retry-After`).
|
|
6
|
+
* The defaults follow the conservative access policy used by
|
|
7
|
+
* hideokamoto/stripe-docs-updates for docs.stripe.com and stripe.com.
|
|
8
|
+
*/
|
|
9
|
+
interface RateLimitOptions {
|
|
10
|
+
/** Delay between consecutive requests in milliseconds. */
|
|
11
|
+
requestDelayMs: number;
|
|
12
|
+
/** Random variation (±half of this value) added to each delay in milliseconds. */
|
|
13
|
+
requestJitterMs: number;
|
|
14
|
+
/** Number of retries after the first attempt for 429 / 5xx responses and network errors. */
|
|
15
|
+
maxRetries: number;
|
|
16
|
+
/** Base delay for exponential backoff in milliseconds. */
|
|
17
|
+
backoffBaseMs: number;
|
|
18
|
+
/** Upper bound for a single backoff delay in milliseconds. */
|
|
19
|
+
backoffMaxMs: number;
|
|
20
|
+
}
|
|
21
|
+
declare const DEFAULT_RATE_LIMIT: Readonly<RateLimitOptions>;
|
|
22
|
+
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
23
|
+
type SleepFn = (ms: number) => Promise<void>;
|
|
24
|
+
declare function resolveRateLimit(options?: Partial<RateLimitOptions>): RateLimitOptions;
|
|
25
|
+
declare function delay(ms: number): Promise<void>;
|
|
26
|
+
declare function withJitter(baseMs: number, jitterMs: number, random?: () => number): number;
|
|
27
|
+
declare function delayWithJitter(baseMs: number, jitterMs: number, sleep?: SleepFn): Promise<void>;
|
|
28
|
+
declare function calculateExponentialBackoff(attempt: number, baseMs: number, maxMs: number): number;
|
|
29
|
+
/**
|
|
30
|
+
* Parse a `Retry-After` header (seconds or HTTP date) into milliseconds.
|
|
31
|
+
* Returns undefined when the header is missing, invalid, or not in the future.
|
|
32
|
+
*/
|
|
33
|
+
declare function parseRetryAfter(value: string | null | undefined, now?: number): number | undefined;
|
|
34
|
+
interface FetchWithRetryOptions {
|
|
35
|
+
rateLimit?: Partial<RateLimitOptions>;
|
|
36
|
+
fetch?: FetchLike;
|
|
37
|
+
sleep?: SleepFn;
|
|
38
|
+
/** Called before each retry; useful for logging. */
|
|
39
|
+
onRetry?: (info: {
|
|
40
|
+
url: string;
|
|
41
|
+
attempt: number;
|
|
42
|
+
waitMs: number;
|
|
43
|
+
reason: string;
|
|
44
|
+
}) => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Fetch a URL, retrying 429 / 5xx responses and network errors.
|
|
48
|
+
*
|
|
49
|
+
* The final response is returned as-is, including non-2xx responses, so the
|
|
50
|
+
* caller decides how to treat 404 and similar statuses. A network error is
|
|
51
|
+
* rethrown after the last retry.
|
|
52
|
+
*/
|
|
53
|
+
declare function fetchWithRetry(url: string, init?: RequestInit, options?: FetchWithRetryOptions): Promise<Response>;
|
|
54
|
+
/**
|
|
55
|
+
* Sequential request pacer: waits `requestDelayMs` (± jitter) before every
|
|
56
|
+
* request except the first one.
|
|
57
|
+
*/
|
|
58
|
+
declare class RequestPacer {
|
|
59
|
+
private readonly limits;
|
|
60
|
+
private readonly sleep;
|
|
61
|
+
private started;
|
|
62
|
+
constructor(limits: RateLimitOptions, sleep?: SleepFn);
|
|
63
|
+
wait(): Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
|
|
1
66
|
/**
|
|
2
67
|
* Utility functions for processing Stripe docs sitemaps
|
|
3
68
|
*/
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Escape a string so it can be embedded in a regular expression literally.
|
|
72
|
+
*/
|
|
73
|
+
declare function escapeRegExp(value: string): string;
|
|
74
|
+
interface SitemapProcessorOptions {
|
|
75
|
+
debug?: boolean;
|
|
76
|
+
logger?: Logger;
|
|
77
|
+
/** Rate limiting and retry settings for sitemap requests. */
|
|
78
|
+
rateLimit?: Partial<RateLimitOptions>;
|
|
79
|
+
/** Custom fetch implementation (defaults to the global fetch). */
|
|
80
|
+
fetch?: FetchLike;
|
|
81
|
+
/** Custom sleep implementation, mainly for tests. */
|
|
82
|
+
sleep?: SleepFn;
|
|
83
|
+
}
|
|
4
84
|
/**
|
|
5
85
|
* Logger interface for SitemapProcessor
|
|
6
86
|
*/
|
|
7
|
-
|
|
87
|
+
interface Logger {
|
|
8
88
|
log(message: string): void;
|
|
9
89
|
error(message: string): void;
|
|
10
90
|
warn(message: string): void;
|
|
@@ -12,7 +92,7 @@ export interface Logger {
|
|
|
12
92
|
/**
|
|
13
93
|
* Default console logger implementation
|
|
14
94
|
*/
|
|
15
|
-
|
|
95
|
+
declare class ConsoleLogger implements Logger {
|
|
16
96
|
private debug;
|
|
17
97
|
constructor(debug?: boolean);
|
|
18
98
|
log(message: string): void;
|
|
@@ -22,17 +102,18 @@ export declare class ConsoleLogger implements Logger {
|
|
|
22
102
|
/**
|
|
23
103
|
* Utility class for processing Stripe docs sitemaps
|
|
24
104
|
*/
|
|
25
|
-
|
|
105
|
+
declare class SitemapProcessor {
|
|
26
106
|
private debug;
|
|
27
107
|
private logger;
|
|
108
|
+
private rateLimit;
|
|
109
|
+
private fetchImpl?;
|
|
110
|
+
private sleep?;
|
|
28
111
|
/**
|
|
29
112
|
* Constructor for SitemapProcessor
|
|
30
113
|
* @param options Configuration options
|
|
31
114
|
*/
|
|
32
|
-
constructor(options?:
|
|
33
|
-
|
|
34
|
-
logger?: Logger;
|
|
35
|
-
});
|
|
115
|
+
constructor(options?: SitemapProcessorOptions);
|
|
116
|
+
private fetchUrl;
|
|
36
117
|
/**
|
|
37
118
|
* Log a message if debug mode is enabled
|
|
38
119
|
* @param message Message to log
|
|
@@ -83,4 +164,5 @@ export declare class SitemapProcessor {
|
|
|
83
164
|
*/
|
|
84
165
|
fetchAndProcessSitemapIndex(indexUrl: string, baseUrl?: string): Promise<string[]>;
|
|
85
166
|
}
|
|
86
|
-
|
|
167
|
+
|
|
168
|
+
export { ConsoleLogger, DEFAULT_RATE_LIMIT, type FetchLike, type FetchWithRetryOptions, type Logger, type RateLimitOptions, RequestPacer, SitemapProcessor, type SitemapProcessorOptions, type SleepFn, calculateExponentialBackoff, delay, delayWithJitter, escapeRegExp, fetchWithRetry, parseRetryAfter, resolveRateLimit, withJitter };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// src/http.ts
|
|
2
|
+
var DEFAULT_RATE_LIMIT = Object.freeze({
|
|
3
|
+
requestDelayMs: 1e3,
|
|
4
|
+
requestJitterMs: 500,
|
|
5
|
+
maxRetries: 3,
|
|
6
|
+
backoffBaseMs: 1e3,
|
|
7
|
+
backoffMaxMs: 3e4
|
|
8
|
+
});
|
|
9
|
+
function resolveRateLimit(options) {
|
|
10
|
+
return { ...DEFAULT_RATE_LIMIT, ...options };
|
|
11
|
+
}
|
|
12
|
+
function delay(ms) {
|
|
13
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
14
|
+
}
|
|
15
|
+
function withJitter(baseMs, jitterMs, random = Math.random) {
|
|
16
|
+
const jitter = random() * jitterMs - jitterMs / 2;
|
|
17
|
+
return Math.max(0, Math.floor(baseMs + jitter));
|
|
18
|
+
}
|
|
19
|
+
async function delayWithJitter(baseMs, jitterMs, sleep = delay) {
|
|
20
|
+
const ms = withJitter(baseMs, jitterMs);
|
|
21
|
+
if (ms > 0) {
|
|
22
|
+
await sleep(ms);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function calculateExponentialBackoff(attempt, baseMs, maxMs) {
|
|
26
|
+
return Math.min(baseMs * Math.pow(2, attempt), maxMs);
|
|
27
|
+
}
|
|
28
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
29
|
+
if (!value) {
|
|
30
|
+
return void 0;
|
|
31
|
+
}
|
|
32
|
+
const trimmed = value.trim();
|
|
33
|
+
if (/^\d+$/.test(trimmed)) {
|
|
34
|
+
const ms2 = Number(trimmed) * 1e3;
|
|
35
|
+
return ms2 > 0 ? ms2 : void 0;
|
|
36
|
+
}
|
|
37
|
+
const date = Date.parse(trimmed);
|
|
38
|
+
if (Number.isNaN(date)) {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
const ms = date - now;
|
|
42
|
+
return ms > 0 ? ms : void 0;
|
|
43
|
+
}
|
|
44
|
+
function isRetryableStatus(status) {
|
|
45
|
+
return status === 429 || status >= 500;
|
|
46
|
+
}
|
|
47
|
+
async function fetchWithRetry(url, init, options = {}) {
|
|
48
|
+
const limits = resolveRateLimit(options.rateLimit);
|
|
49
|
+
const doFetch = options.fetch ?? ((input, reqInit) => fetch(input, reqInit));
|
|
50
|
+
const sleep = options.sleep ?? delay;
|
|
51
|
+
for (let attempt = 0; ; attempt++) {
|
|
52
|
+
let response;
|
|
53
|
+
try {
|
|
54
|
+
response = await doFetch(url, init);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (attempt >= limits.maxRetries) {
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
const waitMs2 = calculateExponentialBackoff(
|
|
60
|
+
attempt,
|
|
61
|
+
limits.backoffBaseMs,
|
|
62
|
+
limits.backoffMaxMs
|
|
63
|
+
);
|
|
64
|
+
options.onRetry?.({ url, attempt: attempt + 1, waitMs: waitMs2, reason: String(error) });
|
|
65
|
+
await delayWithJitter(waitMs2, limits.requestJitterMs, sleep);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (!isRetryableStatus(response.status) || attempt >= limits.maxRetries) {
|
|
69
|
+
return response;
|
|
70
|
+
}
|
|
71
|
+
const retryAfter = parseRetryAfter(response.headers?.get?.("Retry-After"));
|
|
72
|
+
const waitMs = Math.min(
|
|
73
|
+
retryAfter ?? calculateExponentialBackoff(attempt, limits.backoffBaseMs, limits.backoffMaxMs),
|
|
74
|
+
limits.backoffMaxMs
|
|
75
|
+
);
|
|
76
|
+
options.onRetry?.({ url, attempt: attempt + 1, waitMs, reason: `HTTP ${response.status}` });
|
|
77
|
+
await delayWithJitter(waitMs, limits.requestJitterMs, sleep);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
var RequestPacer = class {
|
|
81
|
+
constructor(limits, sleep = delay) {
|
|
82
|
+
this.limits = limits;
|
|
83
|
+
this.sleep = sleep;
|
|
84
|
+
this.started = false;
|
|
85
|
+
}
|
|
86
|
+
async wait() {
|
|
87
|
+
if (this.started) {
|
|
88
|
+
await delayWithJitter(this.limits.requestDelayMs, this.limits.requestJitterMs, this.sleep);
|
|
89
|
+
}
|
|
90
|
+
this.started = true;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// src/index.ts
|
|
95
|
+
function escapeRegExp(value) {
|
|
96
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
97
|
+
}
|
|
98
|
+
var ConsoleLogger = class {
|
|
99
|
+
constructor(debug = false) {
|
|
100
|
+
this.debug = debug;
|
|
101
|
+
}
|
|
102
|
+
log(message) {
|
|
103
|
+
if (this.debug) {
|
|
104
|
+
console.log(message);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
error(message) {
|
|
108
|
+
console.error(message);
|
|
109
|
+
}
|
|
110
|
+
warn(message) {
|
|
111
|
+
if (this.debug) {
|
|
112
|
+
console.warn(message);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
var SitemapProcessor = class {
|
|
117
|
+
/**
|
|
118
|
+
* Constructor for SitemapProcessor
|
|
119
|
+
* @param options Configuration options
|
|
120
|
+
*/
|
|
121
|
+
constructor(options = {}) {
|
|
122
|
+
this.debug = options.debug ?? false;
|
|
123
|
+
this.logger = options.logger ?? new ConsoleLogger(this.debug);
|
|
124
|
+
this.rateLimit = resolveRateLimit(options.rateLimit);
|
|
125
|
+
this.fetchImpl = options.fetch;
|
|
126
|
+
this.sleep = options.sleep;
|
|
127
|
+
}
|
|
128
|
+
fetchUrl(url) {
|
|
129
|
+
return fetchWithRetry(url, void 0, {
|
|
130
|
+
rateLimit: this.rateLimit,
|
|
131
|
+
fetch: this.fetchImpl,
|
|
132
|
+
sleep: this.sleep,
|
|
133
|
+
onRetry: ({ attempt, waitMs, reason }) => this.logWarning(`Retrying ${url} (attempt ${attempt}, ${reason}) in ${waitMs}ms`)
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Log a message if debug mode is enabled
|
|
138
|
+
* @param message Message to log
|
|
139
|
+
*/
|
|
140
|
+
log(message) {
|
|
141
|
+
this.logger.log(message);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Log an error message
|
|
145
|
+
* @param message Error message to log
|
|
146
|
+
*/
|
|
147
|
+
logError(message) {
|
|
148
|
+
this.logger.error(message);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Log a warning message
|
|
152
|
+
* @param message Warning message to log
|
|
153
|
+
*/
|
|
154
|
+
logWarning(message) {
|
|
155
|
+
this.logger.warn(message);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Extract URLs from a sitemap
|
|
159
|
+
* @param content Sitemap XML content
|
|
160
|
+
* @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)
|
|
161
|
+
* @returns Array of extracted URLs
|
|
162
|
+
*/
|
|
163
|
+
extractUrlsFromSitemap(content, baseUrl = "https://docs.stripe.com/") {
|
|
164
|
+
const urlRegex = new RegExp(`<loc>(${escapeRegExp(baseUrl)}[^<]+)</loc>`, "g");
|
|
165
|
+
const urls = [];
|
|
166
|
+
let match;
|
|
167
|
+
while ((match = urlRegex.exec(content)) !== null) {
|
|
168
|
+
urls.push(match[1]);
|
|
169
|
+
}
|
|
170
|
+
return urls;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Extract sitemap URLs from a sitemap index
|
|
174
|
+
* @param content Sitemap index XML content
|
|
175
|
+
* @returns Array of extracted sitemap URLs
|
|
176
|
+
*/
|
|
177
|
+
extractSitemapUrlsFromIndex(content) {
|
|
178
|
+
if (!content || typeof content !== "string") {
|
|
179
|
+
this.logError("Invalid input: content must be a string");
|
|
180
|
+
return [];
|
|
181
|
+
}
|
|
182
|
+
if (!content.includes("<?xml") || !content.includes("<sitemapindex")) {
|
|
183
|
+
this.logError("Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements.");
|
|
184
|
+
return [];
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
const sitemapRegex = /<loc>([^<]+)<\/loc>/g;
|
|
188
|
+
const sitemapUrls = [];
|
|
189
|
+
let match;
|
|
190
|
+
while ((match = sitemapRegex.exec(content)) !== null) {
|
|
191
|
+
const url = match[1];
|
|
192
|
+
try {
|
|
193
|
+
new URL(url);
|
|
194
|
+
sitemapUrls.push(url);
|
|
195
|
+
} catch (urlError) {
|
|
196
|
+
this.logWarning(`Skipped invalid URL format: ${url}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (sitemapUrls.length === 0) {
|
|
200
|
+
this.logWarning("No valid URLs found in sitemap index");
|
|
201
|
+
}
|
|
202
|
+
return sitemapUrls;
|
|
203
|
+
} catch (error) {
|
|
204
|
+
this.logError(`Error extracting URLs from sitemap index: ${error}`);
|
|
205
|
+
return [];
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Find newly added URLs
|
|
210
|
+
* @param currentUrls Current URL list
|
|
211
|
+
* @param previousUrls Previous URL list
|
|
212
|
+
* @returns Array of newly added URLs
|
|
213
|
+
*/
|
|
214
|
+
findNewUrls(currentUrls, previousUrls) {
|
|
215
|
+
const previousUrlSet = new Set(previousUrls);
|
|
216
|
+
return currentUrls.filter((url) => !previousUrlSet.has(url));
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Fetch and process a sitemap
|
|
220
|
+
* @param url Sitemap URL
|
|
221
|
+
* @param baseUrl Base URL part to extract
|
|
222
|
+
* @returns List of retrieved URLs
|
|
223
|
+
*/
|
|
224
|
+
async fetchAndProcessSitemap(url, baseUrl) {
|
|
225
|
+
const response = await this.fetchUrl(url);
|
|
226
|
+
if (!response.ok) {
|
|
227
|
+
throw new Error(`Failed to fetch sitemap: ${response.status} ${response.statusText}`);
|
|
228
|
+
}
|
|
229
|
+
const sitemapContent = await response.text();
|
|
230
|
+
return this.extractUrlsFromSitemap(sitemapContent, baseUrl);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Fetch and process a sitemap index
|
|
234
|
+
* @param indexUrl Sitemap index URL
|
|
235
|
+
* @param baseUrl Base URL part to extract
|
|
236
|
+
* @returns List of retrieved URLs
|
|
237
|
+
*/
|
|
238
|
+
async fetchAndProcessSitemapIndex(indexUrl, baseUrl) {
|
|
239
|
+
this.log(`Fetching sitemap index: ${indexUrl}`);
|
|
240
|
+
const pacer = new RequestPacer(this.rateLimit, this.sleep);
|
|
241
|
+
await pacer.wait();
|
|
242
|
+
const response = await this.fetchUrl(indexUrl);
|
|
243
|
+
if (!response.ok) {
|
|
244
|
+
throw new Error(`Failed to fetch sitemap index: ${response.status} ${response.statusText}`);
|
|
245
|
+
}
|
|
246
|
+
const indexContent = await response.text();
|
|
247
|
+
const sitemapUrls = this.extractSitemapUrlsFromIndex(indexContent);
|
|
248
|
+
this.log(`Number of sitemap partitions: ${sitemapUrls.length}`);
|
|
249
|
+
const allUrls = [];
|
|
250
|
+
for (let i = 0; i < sitemapUrls.length; i++) {
|
|
251
|
+
const sitemapUrl = sitemapUrls[i];
|
|
252
|
+
this.log(`Processing partition ${i + 1}/${sitemapUrls.length}: ${sitemapUrl}`);
|
|
253
|
+
await pacer.wait();
|
|
254
|
+
const urls = await this.fetchAndProcessSitemap(sitemapUrl, baseUrl);
|
|
255
|
+
this.log(`Retrieved ${urls.length} URLs from partition ${i + 1}`);
|
|
256
|
+
allUrls.push(...urls);
|
|
257
|
+
}
|
|
258
|
+
return allUrls;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
export {
|
|
262
|
+
ConsoleLogger,
|
|
263
|
+
DEFAULT_RATE_LIMIT,
|
|
264
|
+
RequestPacer,
|
|
265
|
+
SitemapProcessor,
|
|
266
|
+
calculateExponentialBackoff,
|
|
267
|
+
delay,
|
|
268
|
+
delayWithJitter,
|
|
269
|
+
escapeRegExp,
|
|
270
|
+
fetchWithRetry,
|
|
271
|
+
parseRetryAfter,
|
|
272
|
+
resolveRateLimit,
|
|
273
|
+
withJitter
|
|
274
|
+
};
|
|
275
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/http.ts","../src/index.ts"],"sourcesContent":["/**\n * Rate limiting and retry helpers for fetching Stripe sites.\n *\n * Requests are sent one at a time with a delay between them, and HTTP 429 / 5xx\n * responses are retried with exponential backoff (honouring `Retry-After`).\n * The defaults follow the conservative access policy used by\n * hideokamoto/stripe-docs-updates for docs.stripe.com and stripe.com.\n */\n\nexport interface RateLimitOptions {\n /** Delay between consecutive requests in milliseconds. */\n requestDelayMs: number;\n /** Random variation (±half of this value) added to each delay in milliseconds. */\n requestJitterMs: number;\n /** Number of retries after the first attempt for 429 / 5xx responses and network errors. */\n maxRetries: number;\n /** Base delay for exponential backoff in milliseconds. */\n backoffBaseMs: number;\n /** Upper bound for a single backoff delay in milliseconds. */\n backoffMaxMs: number;\n}\n\nexport const DEFAULT_RATE_LIMIT: Readonly<RateLimitOptions> = Object.freeze({\n requestDelayMs: 1000,\n requestJitterMs: 500,\n maxRetries: 3,\n backoffBaseMs: 1000,\n backoffMaxMs: 30000,\n});\n\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\nexport type SleepFn = (ms: number) => Promise<void>;\n\nexport function resolveRateLimit(options?: Partial<RateLimitOptions>): RateLimitOptions {\n return { ...DEFAULT_RATE_LIMIT, ...options };\n}\n\nexport function delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport function withJitter(baseMs: number, jitterMs: number, random: () => number = Math.random) {\n const jitter = random() * jitterMs - jitterMs / 2;\n return Math.max(0, Math.floor(baseMs + jitter));\n}\n\nexport async function delayWithJitter(\n baseMs: number,\n jitterMs: number,\n sleep: SleepFn = delay\n): Promise<void> {\n const ms = withJitter(baseMs, jitterMs);\n if (ms > 0) {\n await sleep(ms);\n }\n}\n\nexport function calculateExponentialBackoff(attempt: number, baseMs: number, maxMs: number) {\n return Math.min(baseMs * Math.pow(2, attempt), maxMs);\n}\n\n/**\n * Parse a `Retry-After` header (seconds or HTTP date) into milliseconds.\n * Returns undefined when the header is missing, invalid, or not in the future.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number = Date.now()) {\n if (!value) {\n return undefined;\n }\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) {\n const ms = Number(trimmed) * 1000;\n return ms > 0 ? ms : undefined;\n }\n const date = Date.parse(trimmed);\n if (Number.isNaN(date)) {\n return undefined;\n }\n const ms = date - now;\n return ms > 0 ? ms : undefined;\n}\n\nfunction isRetryableStatus(status: number): boolean {\n return status === 429 || status >= 500;\n}\n\nexport interface FetchWithRetryOptions {\n rateLimit?: Partial<RateLimitOptions>;\n fetch?: FetchLike;\n sleep?: SleepFn;\n /** Called before each retry; useful for logging. */\n onRetry?: (info: { url: string; attempt: number; waitMs: number; reason: string }) => void;\n}\n\n/**\n * Fetch a URL, retrying 429 / 5xx responses and network errors.\n *\n * The final response is returned as-is, including non-2xx responses, so the\n * caller decides how to treat 404 and similar statuses. A network error is\n * rethrown after the last retry.\n */\nexport async function fetchWithRetry(\n url: string,\n init?: RequestInit,\n options: FetchWithRetryOptions = {}\n): Promise<Response> {\n const limits = resolveRateLimit(options.rateLimit);\n const doFetch: FetchLike = options.fetch ?? ((input, reqInit) => fetch(input, reqInit));\n const sleep = options.sleep ?? delay;\n\n for (let attempt = 0; ; attempt++) {\n let response: Response;\n try {\n response = await doFetch(url, init);\n } catch (error) {\n if (attempt >= limits.maxRetries) {\n throw error;\n }\n const waitMs = calculateExponentialBackoff(\n attempt,\n limits.backoffBaseMs,\n limits.backoffMaxMs\n );\n options.onRetry?.({ url, attempt: attempt + 1, waitMs, reason: String(error) });\n await delayWithJitter(waitMs, limits.requestJitterMs, sleep);\n continue;\n }\n\n if (!isRetryableStatus(response.status) || attempt >= limits.maxRetries) {\n return response;\n }\n\n const retryAfter = parseRetryAfter(response.headers?.get?.('Retry-After'));\n const waitMs = Math.min(\n retryAfter ?? calculateExponentialBackoff(attempt, limits.backoffBaseMs, limits.backoffMaxMs),\n limits.backoffMaxMs\n );\n options.onRetry?.({ url, attempt: attempt + 1, waitMs, reason: `HTTP ${response.status}` });\n await delayWithJitter(waitMs, limits.requestJitterMs, sleep);\n }\n}\n\n/**\n * Sequential request pacer: waits `requestDelayMs` (± jitter) before every\n * request except the first one.\n */\nexport class RequestPacer {\n private started = false;\n\n constructor(\n private readonly limits: RateLimitOptions,\n private readonly sleep: SleepFn = delay\n ) {}\n\n async wait(): Promise<void> {\n if (this.started) {\n await delayWithJitter(this.limits.requestDelayMs, this.limits.requestJitterMs, this.sleep);\n }\n this.started = true;\n }\n}\n","/**\n * Utility functions for processing Stripe docs sitemaps\n */\n\nimport {\n fetchWithRetry,\n resolveRateLimit,\n RequestPacer,\n type FetchLike,\n type RateLimitOptions,\n type SleepFn,\n} from './http';\n\nexport * from './http';\n\n/**\n * Escape a string so it can be embedded in a regular expression literally.\n */\nexport function escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport interface SitemapProcessorOptions {\n debug?: boolean;\n logger?: Logger;\n /** Rate limiting and retry settings for sitemap requests. */\n rateLimit?: Partial<RateLimitOptions>;\n /** Custom fetch implementation (defaults to the global fetch). */\n fetch?: FetchLike;\n /** Custom sleep implementation, mainly for tests. */\n sleep?: SleepFn;\n}\n\n/**\n * Logger interface for SitemapProcessor\n */\nexport interface Logger {\n log(message: string): void;\n error(message: string): void;\n warn(message: string): void;\n}\n\n/**\n * Default console logger implementation\n */\nexport class ConsoleLogger implements Logger {\n constructor(private debug: boolean = false) {}\n\n log(message: string): void {\n if (this.debug) {\n console.log(message);\n }\n }\n\n error(message: string): void {\n console.error(message);\n }\n\n warn(message: string): void {\n if (this.debug) {\n console.warn(message);\n }\n }\n}\n\n/**\n * Utility class for processing Stripe docs sitemaps\n */\nexport class SitemapProcessor {\n private debug: boolean;\n private logger: Logger;\n private rateLimit: RateLimitOptions;\n private fetchImpl?: FetchLike;\n private sleep?: SleepFn;\n\n /**\n * Constructor for SitemapProcessor\n * @param options Configuration options\n */\n constructor(options: SitemapProcessorOptions = {}) {\n this.debug = options.debug ?? false;\n this.logger = options.logger ?? new ConsoleLogger(this.debug);\n this.rateLimit = resolveRateLimit(options.rateLimit);\n this.fetchImpl = options.fetch;\n this.sleep = options.sleep;\n }\n\n private fetchUrl(url: string): Promise<Response> {\n return fetchWithRetry(url, undefined, {\n rateLimit: this.rateLimit,\n fetch: this.fetchImpl,\n sleep: this.sleep,\n onRetry: ({ attempt, waitMs, reason }) =>\n this.logWarning(`Retrying ${url} (attempt ${attempt}, ${reason}) in ${waitMs}ms`),\n });\n }\n\n /**\n * Log a message if debug mode is enabled\n * @param message Message to log\n */\n private log(message: string): void {\n this.logger.log(message);\n }\n\n /**\n * Log an error message\n * @param message Error message to log\n */\n private logError(message: string): void {\n this.logger.error(message);\n }\n\n /**\n * Log a warning message\n * @param message Warning message to log\n */\n private logWarning(message: string): void {\n this.logger.warn(message);\n }\n\n /**\n * Extract URLs from a sitemap\n * @param content Sitemap XML content\n * @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)\n * @returns Array of extracted URLs\n */\n public extractUrlsFromSitemap(\n content: string,\n baseUrl: string = 'https://docs.stripe.com/'\n ): string[] {\n const urlRegex = new RegExp(`<loc>(${escapeRegExp(baseUrl)}[^<]+)<\\/loc>`, 'g');\n const urls: string[] = [];\n let match;\n\n while ((match = urlRegex.exec(content)) !== null) {\n urls.push(match[1]);\n }\n\n return urls;\n }\n\n /**\n * Extract sitemap URLs from a sitemap index\n * @param content Sitemap index XML content\n * @returns Array of extracted sitemap URLs\n */\n public extractSitemapUrlsFromIndex(content: string): string[] {\n // Input validation\n if (!content || typeof content !== 'string') {\n this.logError('Invalid input: content must be a string');\n return [];\n }\n\n // Basic XML structure validation\n if (!content.includes('<?xml') || !content.includes('<sitemapindex')) {\n this.logError('Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements.');\n return [];\n }\n\n try {\n const sitemapRegex = /<loc>([^<]+)<\\/loc>/g;\n const sitemapUrls: string[] = [];\n let match;\n\n while ((match = sitemapRegex.exec(content)) !== null) {\n // URL validation (optional)\n const url = match[1];\n try {\n new URL(url); // Check if URL is valid\n sitemapUrls.push(url);\n } catch (urlError) {\n this.logWarning(`Skipped invalid URL format: ${url}`);\n // Skip invalid URLs\n }\n }\n\n if (sitemapUrls.length === 0) {\n this.logWarning('No valid URLs found in sitemap index');\n }\n\n return sitemapUrls;\n } catch (error) {\n this.logError(`Error extracting URLs from sitemap index: ${error}`);\n return []; // Return empty array on error\n }\n }\n\n /**\n * Find newly added URLs\n * @param currentUrls Current URL list\n * @param previousUrls Previous URL list\n * @returns Array of newly added URLs\n */\n public findNewUrls(currentUrls: string[], previousUrls: string[]): string[] {\n const previousUrlSet = new Set(previousUrls);\n return currentUrls.filter(url => !previousUrlSet.has(url));\n }\n\n /**\n * Fetch and process a sitemap\n * @param url Sitemap URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemap(url: string, baseUrl?: string): Promise<string[]> {\n const response = await this.fetchUrl(url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap: ${response.status} ${response.statusText}`);\n }\n\n const sitemapContent = await response.text();\n return this.extractUrlsFromSitemap(sitemapContent, baseUrl);\n }\n\n /**\n * Fetch and process a sitemap index\n * @param indexUrl Sitemap index URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemapIndex(indexUrl: string, baseUrl?: string): Promise<string[]> {\n this.log(`Fetching sitemap index: ${indexUrl}`);\n const pacer = new RequestPacer(this.rateLimit, this.sleep);\n await pacer.wait();\n const response = await this.fetchUrl(indexUrl);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap index: ${response.status} ${response.statusText}`);\n }\n\n const indexContent = await response.text();\n const sitemapUrls = this.extractSitemapUrlsFromIndex(indexContent);\n this.log(`Number of sitemap partitions: ${sitemapUrls.length}`);\n\n // Combine URLs from each sitemap file\n const allUrls: string[] = [];\n\n for (let i = 0; i < sitemapUrls.length; i++) {\n const sitemapUrl = sitemapUrls[i];\n this.log(`Processing partition ${i + 1}/${sitemapUrls.length}: ${sitemapUrl}`);\n await pacer.wait();\n const urls = await this.fetchAndProcessSitemap(sitemapUrl, baseUrl);\n this.log(`Retrieved ${urls.length} URLs from partition ${i + 1}`);\n allUrls.push(...urls);\n }\n\n return allUrls;\n }\n}\n"],"mappings":";AAsBO,IAAM,qBAAiD,OAAO,OAAO;AAAA,EAC1E,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,cAAc;AAChB,CAAC;AAKM,SAAS,iBAAiB,SAAuD;AACtF,SAAO,EAAE,GAAG,oBAAoB,GAAG,QAAQ;AAC7C;AAEO,SAAS,MAAM,IAA2B;AAC/C,SAAO,IAAI,QAAQ,aAAW,WAAW,SAAS,EAAE,CAAC;AACvD;AAEO,SAAS,WAAW,QAAgB,UAAkB,SAAuB,KAAK,QAAQ;AAC/F,QAAM,SAAS,OAAO,IAAI,WAAW,WAAW;AAChD,SAAO,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,MAAM,CAAC;AAChD;AAEA,eAAsB,gBACpB,QACA,UACA,QAAiB,OACF;AACf,QAAM,KAAK,WAAW,QAAQ,QAAQ;AACtC,MAAI,KAAK,GAAG;AACV,UAAM,MAAM,EAAE;AAAA,EAChB;AACF;AAEO,SAAS,4BAA4B,SAAiB,QAAgB,OAAe;AAC1F,SAAO,KAAK,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO,GAAG,KAAK;AACtD;AAMO,SAAS,gBAAgB,OAAkC,MAAc,KAAK,IA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S,KAAK;AACzC,UAAM,cAAc,KAAK,4BAA4B,YAAY;AACjE,SAAK,IAAI,iCAAiC,YAAY,MAAM,EAAE;AAG9D,UAAM,UAAoB,CAAC;AAE3B,aAAS,IAAI,GAAG,IAAI,YAAY,QAAQ,KAAK;AAC3C,YAAM,aAAa,YAAY,CAAC;AAChC,WAAK,IAAI,wBAAwB,IAAI,CAAC,IAAI,YAAY,MAAM,KAAK,UAAU,EAAE;AAC7E,YAAM,MAAM,KAAK;AACjB,YAAM,OAAO,MAAM,KAAK,uBAAuB,YAAY,OAAO;AAClE,WAAK,IAAI,aAAa,KAAK,MAAM,wBAAwB,IAAI,CAAC,EAAE;AAChE,cAAQ,KAAK,GAAG,IAAI;AAAA,IACtB;AAEA,WAAO;AAAA,EACT;AACF;","names":["ms","waitMs"]}
|
package/package.json
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stripe-loaders-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"main": "./dist/
|
|
6
|
-
"module": "./dist/
|
|
5
|
+
"main": "./dist/index.cjs",
|
|
6
|
+
"module": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
"import": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"require": {
|
|
15
|
+
"types": "./dist/index.d.cts",
|
|
16
|
+
"default": "./dist/index.cjs"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
14
20
|
},
|
|
15
21
|
"files": [
|
|
16
22
|
"dist"
|
|
17
23
|
],
|
|
18
|
-
"scripts": {
|
|
19
|
-
"dev": "vite build --watch",
|
|
20
|
-
"build": "vite build && tsc --emitDeclarationOnly",
|
|
21
|
-
"test": "vitest run",
|
|
22
|
-
"prepublishOnly": "npm run build"
|
|
23
|
-
},
|
|
24
24
|
"keywords": [
|
|
25
25
|
"stripe",
|
|
26
26
|
"documentation",
|
|
@@ -33,14 +33,23 @@
|
|
|
33
33
|
"description": "Core library for Stripe loaders",
|
|
34
34
|
"repository": {
|
|
35
35
|
"type": "git",
|
|
36
|
-
"url": "https://github.com/
|
|
36
|
+
"url": "https://github.com/hideokamoto/stripe-docs-loader",
|
|
37
37
|
"directory": "packages/core"
|
|
38
38
|
},
|
|
39
39
|
"bugs": {
|
|
40
|
-
"url": "https://github.com/
|
|
40
|
+
"url": "https://github.com/hideokamoto/stripe-docs-loader/issues"
|
|
41
41
|
},
|
|
42
|
-
"homepage": "https://github.com/
|
|
42
|
+
"homepage": "https://github.com/hideokamoto/stripe-docs-loader/tree/main/packages/core#readme",
|
|
43
43
|
"publishConfig": {
|
|
44
44
|
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"sideEffects": false,
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=20"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"dev": "tsup --watch",
|
|
52
|
+
"build": "tsup",
|
|
53
|
+
"test": "vitest run"
|
|
45
54
|
}
|
|
46
|
-
}
|
|
55
|
+
}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,MAAM,WAAW,MAAM;IACrB,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED;;GAEG;AACH,qBAAa,aAAc,YAAW,MAAM;IAC9B,OAAO,CAAC,KAAK;gBAAL,KAAK,GAAE,OAAe;IAE1C,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAM1B,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAI5B,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;CAK5B;AAED;;GAEG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,KAAK,CAAU;IACvB,OAAO,CAAC,MAAM,CAAS;IAEvB;;;OAGG;gBACS,OAAO,GAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO;IAK9D;;;OAGG;IACH,OAAO,CAAC,GAAG;IAIX;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAIhB;;;OAGG;IACH,OAAO,CAAC,UAAU;IAIlB;;;;;OAKG;IACI,sBAAsB,CAC3B,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,MAAmC,GAC3C,MAAM,EAAE;IAYX;;;;OAIG;IACI,2BAA2B,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE;IAyC7D;;;;;OAKG;IACI,WAAW,CAAC,WAAW,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE;IAK3E;;;;;OAKG;IACU,sBAAsB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAWrF;;;;;OAKG;IACU,2BAA2B,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;CAyBhG"}
|
package/dist/index.spec.d.ts
DELETED
package/dist/index.spec.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.spec.d.ts","sourceRoot":"","sources":["../src/index.spec.ts"],"names":[],"mappings":""}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class c{constructor(t=!1){this.debug=t}log(t){this.debug&&console.log(t)}error(t){console.error(t)}warn(t){this.debug&&console.warn(t)}}class h{constructor(t={}){this.debug=t.debug??!1,this.logger=t.logger??new c(this.debug)}log(t){this.logger.log(t)}logError(t){this.logger.error(t)}logWarning(t){this.logger.warn(t)}extractUrlsFromSitemap(t,r="https://docs.stripe.com/"){const e=new RegExp(`<loc>(${r}[^<]+)</loc>`,"g"),s=[];let o;for(;(o=e.exec(t))!==null;)s.push(o[1]);return s}extractSitemapUrlsFromIndex(t){if(!t||typeof t!="string")return this.logError("Invalid input: content must be a string"),[];if(!t.includes("<?xml")||!t.includes("<sitemapindex"))return this.logError("Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements."),[];try{const r=/<loc>([^<]+)<\/loc>/g,e=[];let s;for(;(s=r.exec(t))!==null;){const o=s[1];try{new URL(o),e.push(o)}catch{this.logWarning(`Skipped invalid URL format: ${o}`)}}return e.length===0&&this.logWarning("No valid URLs found in sitemap index"),e}catch(r){return this.logError(`Error extracting URLs from sitemap index: ${r}`),[]}}findNewUrls(t,r){const e=new Set(r);return t.filter(s=>!e.has(s))}async fetchAndProcessSitemap(t,r){const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch sitemap: ${e.status} ${e.statusText}`);const s=await e.text();return this.extractUrlsFromSitemap(s,r)}async fetchAndProcessSitemapIndex(t,r){this.log(`Fetching sitemap index: ${t}`);const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch sitemap index: ${e.status} ${e.statusText}`);const s=await e.text(),o=this.extractSitemapUrlsFromIndex(s);this.log(`Number of sitemap partitions: ${o.length}`);const n=[];for(let i=0;i<o.length;i++){const l=o[i];this.log(`Processing partition ${i+1}/${o.length}: ${l}`);const a=await this.fetchAndProcessSitemap(l,r);this.log(`Retrieved ${a.length} URLs from partition ${i+1}`),n.push(...a)}return n}}exports.ConsoleLogger=c;exports.SitemapProcessor=h;
|
|
2
|
-
//# sourceMappingURL=stripe-loaders-core.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stripe-loaders-core.cjs","sources":["../src/index.ts"],"sourcesContent":["/**\n * Utility functions for processing Stripe docs sitemaps\n */\n\n/**\n * Logger interface for SitemapProcessor\n */\nexport interface Logger {\n log(message: string): void;\n error(message: string): void;\n warn(message: string): void;\n}\n\n/**\n * Default console logger implementation\n */\nexport class ConsoleLogger implements Logger {\n constructor(private debug: boolean = false) {}\n\n log(message: string): void {\n if (this.debug) {\n console.log(message);\n }\n }\n\n error(message: string): void {\n console.error(message);\n }\n\n warn(message: string): void {\n if (this.debug) {\n console.warn(message);\n }\n }\n}\n\n/**\n * Utility class for processing Stripe docs sitemaps\n */\nexport class SitemapProcessor {\n private debug: boolean;\n private logger: Logger;\n\n /**\n * Constructor for SitemapProcessor\n * @param options Configuration options\n */\n constructor(options: { debug?: boolean; logger?: Logger } = {}) {\n this.debug = options.debug ?? false;\n this.logger = options.logger ?? new ConsoleLogger(this.debug);\n }\n\n /**\n * Log a message if debug mode is enabled\n * @param message Message to log\n */\n private log(message: string): void {\n this.logger.log(message);\n }\n\n /**\n * Log an error message\n * @param message Error message to log\n */\n private logError(message: string): void {\n this.logger.error(message);\n }\n\n /**\n * Log a warning message\n * @param message Warning message to log\n */\n private logWarning(message: string): void {\n this.logger.warn(message);\n }\n\n /**\n * Extract URLs from a sitemap\n * @param content Sitemap XML content\n * @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)\n * @returns Array of extracted URLs\n */\n public extractUrlsFromSitemap(\n content: string,\n baseUrl: string = 'https://docs.stripe.com/'\n ): string[] {\n const urlRegex = new RegExp(`<loc>(${baseUrl}[^<]+)<\\/loc>`, 'g');\n const urls: string[] = [];\n let match;\n\n while ((match = urlRegex.exec(content)) !== null) {\n urls.push(match[1]);\n }\n\n return urls;\n }\n\n /**\n * Extract sitemap URLs from a sitemap index\n * @param content Sitemap index XML content\n * @returns Array of extracted sitemap URLs\n */\n public extractSitemapUrlsFromIndex(content: string): string[] {\n // Input validation\n if (!content || typeof content !== 'string') {\n this.logError('Invalid input: content must be a string');\n return [];\n }\n\n // Basic XML structure validation\n if (!content.includes('<?xml') || !content.includes('<sitemapindex')) {\n this.logError('Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements.');\n return [];\n }\n\n try {\n const sitemapRegex = /<loc>([^<]+)<\\/loc>/g;\n const sitemapUrls: string[] = [];\n let match;\n\n while ((match = sitemapRegex.exec(content)) !== null) {\n // URL validation (optional)\n const url = match[1];\n try {\n new URL(url); // Check if URL is valid\n sitemapUrls.push(url);\n } catch (urlError) {\n this.logWarning(`Skipped invalid URL format: ${url}`);\n // Skip invalid URLs\n }\n }\n\n if (sitemapUrls.length === 0) {\n this.logWarning('No valid URLs found in sitemap index');\n }\n\n return sitemapUrls;\n } catch (error) {\n this.logError(`Error extracting URLs from sitemap index: ${error}`);\n return []; // Return empty array on error\n }\n }\n\n /**\n * Find newly added URLs\n * @param currentUrls Current URL list\n * @param previousUrls Previous URL list\n * @returns Array of newly added URLs\n */\n public findNewUrls(currentUrls: string[], previousUrls: string[]): string[] {\n const previousUrlSet = new Set(previousUrls);\n return currentUrls.filter(url => !previousUrlSet.has(url));\n }\n\n /**\n * Fetch and process a sitemap\n * @param url Sitemap URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemap(url: string, baseUrl?: string): Promise<string[]> {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap: ${response.status} ${response.statusText}`);\n }\n\n const sitemapContent = await response.text();\n return this.extractUrlsFromSitemap(sitemapContent, baseUrl);\n }\n\n /**\n * Fetch and process a sitemap index\n * @param indexUrl Sitemap index URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemapIndex(indexUrl: string, baseUrl?: string): Promise<string[]> {\n this.log(`Fetching sitemap index: ${indexUrl}`);\n const response = await fetch(indexUrl);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap index: ${response.status} ${response.statusText}`);\n }\n\n const indexContent = await response.text();\n const sitemapUrls = this.extractSitemapUrlsFromIndex(indexContent);\n this.log(`Number of sitemap partitions: ${sitemapUrls.length}`);\n\n // Combine URLs from each sitemap file\n const allUrls: string[] = [];\n\n for (let i = 0; i < sitemapUrls.length; i++) {\n const sitemapUrl = sitemapUrls[i];\n this.log(`Processing partition ${i + 1}/${sitemapUrls.length}: ${sitemapUrl}`);\n const urls = await this.fetchAndProcessSitemap(sitemapUrl, baseUrl);\n this.log(`Retrieved ${urls.length} URLs from partition ${i + 1}`);\n allUrls.push(...urls);\n }\n\n return allUrls;\n }\n}\n"],"names":["ConsoleLogger","debug","message","SitemapProcessor","options","content","baseUrl","urlRegex","urls","match","sitemapRegex","sitemapUrls","url","error","currentUrls","previousUrls","previousUrlSet","response","sitemapContent","indexUrl","indexContent","allUrls","sitemapUrl"],"mappings":"gFAgBO,MAAMA,CAAgC,CAC3C,YAAoBC,EAAiB,GAAO,CAAxB,KAAA,MAAAA,CAAA,CAEpB,IAAIC,EAAuB,CACrB,KAAK,OACP,QAAQ,IAAIA,CAAO,CACrB,CAGF,MAAMA,EAAuB,CAC3B,QAAQ,MAAMA,CAAO,CAAA,CAGvB,KAAKA,EAAuB,CACtB,KAAK,OACP,QAAQ,KAAKA,CAAO,CACtB,CAEJ,CAKO,MAAMC,CAAiB,CAQ5B,YAAYC,EAAgD,GAAI,CACzD,KAAA,MAAQA,EAAQ,OAAS,GAC9B,KAAK,OAASA,EAAQ,QAAU,IAAIJ,EAAc,KAAK,KAAK,CAAA,CAOtD,IAAIE,EAAuB,CAC5B,KAAA,OAAO,IAAIA,CAAO,CAAA,CAOjB,SAASA,EAAuB,CACjC,KAAA,OAAO,MAAMA,CAAO,CAAA,CAOnB,WAAWA,EAAuB,CACnC,KAAA,OAAO,KAAKA,CAAO,CAAA,CASnB,uBAC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S5D,MAAa,4BAA4Ba,EAAkBb,EAAqC,CACzF,KAAA,IAAI,2BAA2Ba,CAAQ,EAAE,EACxC,MAAAF,EAAW,MAAM,MAAME,CAAQ,EAEjC,GAAA,CAACF,EAAS,GACN,MAAA,IAAI,MAAM,kCAAkCA,EAAS,MAAM,IAAIA,EAAS,UAAU,EAAE,EAGtF,MAAAG,EAAe,MAAMH,EAAS,KAAK,EACnCN,EAAc,KAAK,4BAA4BS,CAAY,EACjE,KAAK,IAAI,iCAAiCT,EAAY,MAAM,EAAE,EAG9D,MAAMU,EAAoB,CAAC,EAE3B,QAAS,EAAI,EAAG,EAAIV,EAAY,OAAQ,IAAK,CACrC,MAAAW,EAAaX,EAAY,CAAC,EAC3B,KAAA,IAAI,wBAAwB,EAAI,CAAC,IAAIA,EAAY,MAAM,KAAKW,CAAU,EAAE,EAC7E,MAAMd,EAAO,MAAM,KAAK,uBAAuBc,EAAYhB,CAAO,EAClE,KAAK,IAAI,aAAaE,EAAK,MAAM,wBAAwB,EAAI,CAAC,EAAE,EACxDa,EAAA,KAAK,GAAGb,CAAI,CAAA,CAGf,OAAAa,CAAA,CAEX"}
|
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
class g {
|
|
2
|
-
constructor(t = !1) {
|
|
3
|
-
this.debug = t;
|
|
4
|
-
}
|
|
5
|
-
log(t) {
|
|
6
|
-
this.debug && console.log(t);
|
|
7
|
-
}
|
|
8
|
-
error(t) {
|
|
9
|
-
console.error(t);
|
|
10
|
-
}
|
|
11
|
-
warn(t) {
|
|
12
|
-
this.debug && console.warn(t);
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
class h {
|
|
16
|
-
/**
|
|
17
|
-
* Constructor for SitemapProcessor
|
|
18
|
-
* @param options Configuration options
|
|
19
|
-
*/
|
|
20
|
-
constructor(t = {}) {
|
|
21
|
-
this.debug = t.debug ?? !1, this.logger = t.logger ?? new g(this.debug);
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Log a message if debug mode is enabled
|
|
25
|
-
* @param message Message to log
|
|
26
|
-
*/
|
|
27
|
-
log(t) {
|
|
28
|
-
this.logger.log(t);
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Log an error message
|
|
32
|
-
* @param message Error message to log
|
|
33
|
-
*/
|
|
34
|
-
logError(t) {
|
|
35
|
-
this.logger.error(t);
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Log a warning message
|
|
39
|
-
* @param message Warning message to log
|
|
40
|
-
*/
|
|
41
|
-
logWarning(t) {
|
|
42
|
-
this.logger.warn(t);
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Extract URLs from a sitemap
|
|
46
|
-
* @param content Sitemap XML content
|
|
47
|
-
* @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)
|
|
48
|
-
* @returns Array of extracted URLs
|
|
49
|
-
*/
|
|
50
|
-
extractUrlsFromSitemap(t, r = "https://docs.stripe.com/") {
|
|
51
|
-
const e = new RegExp(`<loc>(${r}[^<]+)</loc>`, "g"), s = [];
|
|
52
|
-
let i;
|
|
53
|
-
for (; (i = e.exec(t)) !== null; )
|
|
54
|
-
s.push(i[1]);
|
|
55
|
-
return s;
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Extract sitemap URLs from a sitemap index
|
|
59
|
-
* @param content Sitemap index XML content
|
|
60
|
-
* @returns Array of extracted sitemap URLs
|
|
61
|
-
*/
|
|
62
|
-
extractSitemapUrlsFromIndex(t) {
|
|
63
|
-
if (!t || typeof t != "string")
|
|
64
|
-
return this.logError("Invalid input: content must be a string"), [];
|
|
65
|
-
if (!t.includes("<?xml") || !t.includes("<sitemapindex"))
|
|
66
|
-
return this.logError("Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements."), [];
|
|
67
|
-
try {
|
|
68
|
-
const r = /<loc>([^<]+)<\/loc>/g, e = [];
|
|
69
|
-
let s;
|
|
70
|
-
for (; (s = r.exec(t)) !== null; ) {
|
|
71
|
-
const i = s[1];
|
|
72
|
-
try {
|
|
73
|
-
new URL(i), e.push(i);
|
|
74
|
-
} catch {
|
|
75
|
-
this.logWarning(`Skipped invalid URL format: ${i}`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
return e.length === 0 && this.logWarning("No valid URLs found in sitemap index"), e;
|
|
79
|
-
} catch (r) {
|
|
80
|
-
return this.logError(`Error extracting URLs from sitemap index: ${r}`), [];
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Find newly added URLs
|
|
85
|
-
* @param currentUrls Current URL list
|
|
86
|
-
* @param previousUrls Previous URL list
|
|
87
|
-
* @returns Array of newly added URLs
|
|
88
|
-
*/
|
|
89
|
-
findNewUrls(t, r) {
|
|
90
|
-
const e = new Set(r);
|
|
91
|
-
return t.filter((s) => !e.has(s));
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Fetch and process a sitemap
|
|
95
|
-
* @param url Sitemap URL
|
|
96
|
-
* @param baseUrl Base URL part to extract
|
|
97
|
-
* @returns List of retrieved URLs
|
|
98
|
-
*/
|
|
99
|
-
async fetchAndProcessSitemap(t, r) {
|
|
100
|
-
const e = await fetch(t);
|
|
101
|
-
if (!e.ok)
|
|
102
|
-
throw new Error(`Failed to fetch sitemap: ${e.status} ${e.statusText}`);
|
|
103
|
-
const s = await e.text();
|
|
104
|
-
return this.extractUrlsFromSitemap(s, r);
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* Fetch and process a sitemap index
|
|
108
|
-
* @param indexUrl Sitemap index URL
|
|
109
|
-
* @param baseUrl Base URL part to extract
|
|
110
|
-
* @returns List of retrieved URLs
|
|
111
|
-
*/
|
|
112
|
-
async fetchAndProcessSitemapIndex(t, r) {
|
|
113
|
-
this.log(`Fetching sitemap index: ${t}`);
|
|
114
|
-
const e = await fetch(t);
|
|
115
|
-
if (!e.ok)
|
|
116
|
-
throw new Error(`Failed to fetch sitemap index: ${e.status} ${e.statusText}`);
|
|
117
|
-
const s = await e.text(), i = this.extractSitemapUrlsFromIndex(s);
|
|
118
|
-
this.log(`Number of sitemap partitions: ${i.length}`);
|
|
119
|
-
const n = [];
|
|
120
|
-
for (let o = 0; o < i.length; o++) {
|
|
121
|
-
const l = i[o];
|
|
122
|
-
this.log(`Processing partition ${o + 1}/${i.length}: ${l}`);
|
|
123
|
-
const a = await this.fetchAndProcessSitemap(l, r);
|
|
124
|
-
this.log(`Retrieved ${a.length} URLs from partition ${o + 1}`), n.push(...a);
|
|
125
|
-
}
|
|
126
|
-
return n;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
export {
|
|
130
|
-
g as ConsoleLogger,
|
|
131
|
-
h as SitemapProcessor
|
|
132
|
-
};
|
|
133
|
-
//# sourceMappingURL=stripe-loaders-core.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stripe-loaders-core.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * Utility functions for processing Stripe docs sitemaps\n */\n\n/**\n * Logger interface for SitemapProcessor\n */\nexport interface Logger {\n log(message: string): void;\n error(message: string): void;\n warn(message: string): void;\n}\n\n/**\n * Default console logger implementation\n */\nexport class ConsoleLogger implements Logger {\n constructor(private debug: boolean = false) {}\n\n log(message: string): void {\n if (this.debug) {\n console.log(message);\n }\n }\n\n error(message: string): void {\n console.error(message);\n }\n\n warn(message: string): void {\n if (this.debug) {\n console.warn(message);\n }\n }\n}\n\n/**\n * Utility class for processing Stripe docs sitemaps\n */\nexport class SitemapProcessor {\n private debug: boolean;\n private logger: Logger;\n\n /**\n * Constructor for SitemapProcessor\n * @param options Configuration options\n */\n constructor(options: { debug?: boolean; logger?: Logger } = {}) {\n this.debug = options.debug ?? false;\n this.logger = options.logger ?? new ConsoleLogger(this.debug);\n }\n\n /**\n * Log a message if debug mode is enabled\n * @param message Message to log\n */\n private log(message: string): void {\n this.logger.log(message);\n }\n\n /**\n * Log an error message\n * @param message Error message to log\n */\n private logError(message: string): void {\n this.logger.error(message);\n }\n\n /**\n * Log a warning message\n * @param message Warning message to log\n */\n private logWarning(message: string): void {\n this.logger.warn(message);\n }\n\n /**\n * Extract URLs from a sitemap\n * @param content Sitemap XML content\n * @param baseUrl Base URL part to extract (e.g., https://docs.stripe.com/)\n * @returns Array of extracted URLs\n */\n public extractUrlsFromSitemap(\n content: string,\n baseUrl: string = 'https://docs.stripe.com/'\n ): string[] {\n const urlRegex = new RegExp(`<loc>(${baseUrl}[^<]+)<\\/loc>`, 'g');\n const urls: string[] = [];\n let match;\n\n while ((match = urlRegex.exec(content)) !== null) {\n urls.push(match[1]);\n }\n\n return urls;\n }\n\n /**\n * Extract sitemap URLs from a sitemap index\n * @param content Sitemap index XML content\n * @returns Array of extracted sitemap URLs\n */\n public extractSitemapUrlsFromIndex(content: string): string[] {\n // Input validation\n if (!content || typeof content !== 'string') {\n this.logError('Invalid input: content must be a string');\n return [];\n }\n\n // Basic XML structure validation\n if (!content.includes('<?xml') || !content.includes('<sitemapindex')) {\n this.logError('Invalid sitemap index XML: Missing <?xml or <sitemapindex> elements.');\n return [];\n }\n\n try {\n const sitemapRegex = /<loc>([^<]+)<\\/loc>/g;\n const sitemapUrls: string[] = [];\n let match;\n\n while ((match = sitemapRegex.exec(content)) !== null) {\n // URL validation (optional)\n const url = match[1];\n try {\n new URL(url); // Check if URL is valid\n sitemapUrls.push(url);\n } catch (urlError) {\n this.logWarning(`Skipped invalid URL format: ${url}`);\n // Skip invalid URLs\n }\n }\n\n if (sitemapUrls.length === 0) {\n this.logWarning('No valid URLs found in sitemap index');\n }\n\n return sitemapUrls;\n } catch (error) {\n this.logError(`Error extracting URLs from sitemap index: ${error}`);\n return []; // Return empty array on error\n }\n }\n\n /**\n * Find newly added URLs\n * @param currentUrls Current URL list\n * @param previousUrls Previous URL list\n * @returns Array of newly added URLs\n */\n public findNewUrls(currentUrls: string[], previousUrls: string[]): string[] {\n const previousUrlSet = new Set(previousUrls);\n return currentUrls.filter(url => !previousUrlSet.has(url));\n }\n\n /**\n * Fetch and process a sitemap\n * @param url Sitemap URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemap(url: string, baseUrl?: string): Promise<string[]> {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap: ${response.status} ${response.statusText}`);\n }\n\n const sitemapContent = await response.text();\n return this.extractUrlsFromSitemap(sitemapContent, baseUrl);\n }\n\n /**\n * Fetch and process a sitemap index\n * @param indexUrl Sitemap index URL\n * @param baseUrl Base URL part to extract\n * @returns List of retrieved URLs\n */\n public async fetchAndProcessSitemapIndex(indexUrl: string, baseUrl?: string): Promise<string[]> {\n this.log(`Fetching sitemap index: ${indexUrl}`);\n const response = await fetch(indexUrl);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch sitemap index: ${response.status} ${response.statusText}`);\n }\n\n const indexContent = await response.text();\n const sitemapUrls = this.extractSitemapUrlsFromIndex(indexContent);\n this.log(`Number of sitemap partitions: ${sitemapUrls.length}`);\n\n // Combine URLs from each sitemap file\n const allUrls: string[] = [];\n\n for (let i = 0; i < sitemapUrls.length; i++) {\n const sitemapUrl = sitemapUrls[i];\n this.log(`Processing partition ${i + 1}/${sitemapUrls.length}: ${sitemapUrl}`);\n const urls = await this.fetchAndProcessSitemap(sitemapUrl, baseUrl);\n this.log(`Retrieved ${urls.length} URLs from partition ${i + 1}`);\n allUrls.push(...urls);\n }\n\n return allUrls;\n }\n}\n"],"names":["ConsoleLogger","debug","message","SitemapProcessor","options","content","baseUrl","urlRegex","urls","match","sitemapRegex","sitemapUrls","url","error","currentUrls","previousUrls","previousUrlSet","response","sitemapContent","indexUrl","indexContent","allUrls","i","sitemapUrl"],"mappings":"AAgBO,MAAMA,EAAgC;AAAA,EAC3C,YAAoBC,IAAiB,IAAO;AAAxB,SAAA,QAAAA;AAAA,EAAA;AAAA,EAEpB,IAAIC,GAAuB;AACzB,IAAI,KAAK,SACP,QAA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