scrapex 1.0.0-beta.1 → 1.0.0-beta.2

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.
Files changed (52) hide show
  1. package/dist/embeddings/index.cjs +52 -0
  2. package/dist/embeddings/index.d.cts +3 -0
  3. package/dist/embeddings/index.d.mts +3 -0
  4. package/dist/embeddings/index.mjs +4 -0
  5. package/dist/embeddings-BjNTQSG9.cjs +1455 -0
  6. package/dist/embeddings-BjNTQSG9.cjs.map +1 -0
  7. package/dist/embeddings-Bsymy_jA.mjs +1215 -0
  8. package/dist/embeddings-Bsymy_jA.mjs.map +1 -0
  9. package/dist/enhancer-Cs_WyWtJ.cjs +219 -0
  10. package/dist/enhancer-Cs_WyWtJ.cjs.map +1 -0
  11. package/dist/enhancer-INx5NlgO.mjs +177 -0
  12. package/dist/enhancer-INx5NlgO.mjs.map +1 -0
  13. package/dist/{enhancer-j0xqKDJm.cjs → http-base-CHLf-Tco.cjs} +36 -199
  14. package/dist/http-base-CHLf-Tco.cjs.map +1 -0
  15. package/dist/{enhancer-ByjRD-t5.mjs → http-base-DM7YNo6X.mjs} +25 -176
  16. package/dist/http-base-DM7YNo6X.mjs.map +1 -0
  17. package/dist/{index-CDgcRnig.d.cts → index-Bvseqli-.d.cts} +1 -1
  18. package/dist/{index-CDgcRnig.d.cts.map → index-Bvseqli-.d.cts.map} +1 -1
  19. package/dist/{index-piS5wtki.d.mts → index-CIFjNySr.d.mts} +1 -1
  20. package/dist/{index-piS5wtki.d.mts.map → index-CIFjNySr.d.mts.map} +1 -1
  21. package/dist/index-D6qfjmZQ.d.mts +401 -0
  22. package/dist/index-D6qfjmZQ.d.mts.map +1 -0
  23. package/dist/index-RFSpP5g8.d.cts +401 -0
  24. package/dist/index-RFSpP5g8.d.cts.map +1 -0
  25. package/dist/index.cjs +39 -1074
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +3 -260
  28. package/dist/index.d.cts.map +1 -1
  29. package/dist/index.d.mts +3 -260
  30. package/dist/index.d.mts.map +1 -1
  31. package/dist/index.mjs +4 -1039
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/llm/index.cjs +7 -6
  34. package/dist/llm/index.cjs.map +1 -1
  35. package/dist/llm/index.d.cts +1 -1
  36. package/dist/llm/index.d.mts +1 -1
  37. package/dist/llm/index.mjs +2 -1
  38. package/dist/llm/index.mjs.map +1 -1
  39. package/dist/parsers/index.d.cts +1 -1
  40. package/dist/parsers/index.d.mts +1 -1
  41. package/dist/parsers/index.mjs +1 -1
  42. package/dist/{parsers-CwkYnyWY.mjs → parsers-DsawHeo0.mjs} +1 -1
  43. package/dist/{parsers-CwkYnyWY.mjs.map → parsers-DsawHeo0.mjs.map} +1 -1
  44. package/dist/{types-CadAXrme.d.mts → types-BOcHQU9s.d.mts} +308 -151
  45. package/dist/types-BOcHQU9s.d.mts.map +1 -0
  46. package/dist/{types-DPEtPihB.d.cts → types-DutdBpqd.d.cts} +308 -151
  47. package/dist/types-DutdBpqd.d.cts.map +1 -0
  48. package/package.json +1 -1
  49. package/dist/enhancer-ByjRD-t5.mjs.map +0 -1
  50. package/dist/enhancer-j0xqKDJm.cjs.map +0 -1
  51. package/dist/types-CadAXrme.d.mts.map +0 -1
  52. package/dist/types-DPEtPihB.d.cts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
- import { c as BaseHttpProvider, d as Semaphore, f as withResilience, l as CircuitBreaker, n as enhance, p as ScrapeError, r as extract, u as RateLimiter } from "./enhancer-ByjRD-t5.mjs";
2
- import { t as RSSParser } from "./parsers-CwkYnyWY.mjs";
1
+ import { d as ScrapeError } from "./http-base-DM7YNo6X.mjs";
2
+ import { F as aggregateVectors, I as cosineSimilarity, O as InMemoryEmbeddingCache, S as chunkText, _ as createHttpEmbedding, a as createPiiRedactor, f as createHuggingFaceEmbedding, h as createTransformersEmbedding, l as TRANSFORMERS_MODELS, m as createOpenAIEmbedding, n as embedScrapedData, o as redactPii, p as createOllamaEmbedding, r as generateEmbeddings, s as createEmbeddingProvider, t as embed, u as createAzureEmbedding, w as estimateTokens } from "./embeddings-Bsymy_jA.mjs";
3
+ import { n as enhance, r as extract } from "./enhancer-INx5NlgO.mjs";
4
+ import { t as RSSParser } from "./parsers-DsawHeo0.mjs";
3
5
  import * as cheerio from "cheerio";
4
- import { createHash } from "node:crypto";
5
6
  import { Readability } from "@mozilla/readability";
6
7
  import TurndownService from "turndown";
7
8
 
@@ -54,1042 +55,6 @@ function mergeResults(context, extracted) {
54
55
  };
55
56
  }
56
57
 
57
- //#endregion
58
- //#region src/embeddings/aggregation.ts
59
- /**
60
- * Aggregate multiple embedding vectors into a single vector or return all.
61
- *
62
- * @param vectors - Array of embedding vectors (must all have same dimensions)
63
- * @param strategy - Aggregation strategy
64
- * @returns Aggregated result based on strategy
65
- */
66
- function aggregateVectors(vectors, strategy = "average") {
67
- if (vectors.length === 0) throw new Error("Cannot aggregate empty vector array");
68
- const firstVector = vectors[0];
69
- if (!firstVector) throw new Error("Cannot aggregate empty vector array");
70
- const dimensions = firstVector.length;
71
- for (let i = 1; i < vectors.length; i++) {
72
- const vec = vectors[i];
73
- if (!vec || vec.length !== dimensions) throw new Error(`Vector dimension mismatch: expected ${dimensions}, got ${vec?.length ?? 0} at index ${i}`);
74
- }
75
- switch (strategy) {
76
- case "average": return {
77
- type: "single",
78
- vector: averageVectors(vectors),
79
- dimensions
80
- };
81
- case "max": return {
82
- type: "single",
83
- vector: maxPoolVectors(vectors),
84
- dimensions
85
- };
86
- case "first": return {
87
- type: "single",
88
- vector: firstVector,
89
- dimensions
90
- };
91
- case "all": return {
92
- type: "multiple",
93
- vectors,
94
- dimensions
95
- };
96
- default: {
97
- const _exhaustive = strategy;
98
- throw new Error(`Unknown aggregation strategy: ${_exhaustive}`);
99
- }
100
- }
101
- }
102
- /**
103
- * Compute element-wise average of vectors.
104
- */
105
- function averageVectors(vectors) {
106
- const first = vectors[0];
107
- if (!first || vectors.length === 1) return first ?? [];
108
- const dimensions = first.length;
109
- const count = vectors.length;
110
- const result = new Array(dimensions).fill(0);
111
- for (const vector of vectors) for (let i = 0; i < dimensions; i++) {
112
- const val = result[i];
113
- if (val !== void 0) result[i] = val + (vector[i] ?? 0);
114
- }
115
- for (let i = 0; i < dimensions; i++) {
116
- const val = result[i];
117
- if (val !== void 0) result[i] = val / count;
118
- }
119
- return result;
120
- }
121
- /**
122
- * Compute element-wise maximum of vectors (max pooling).
123
- */
124
- function maxPoolVectors(vectors) {
125
- const first = vectors[0];
126
- if (!first || vectors.length === 1) return first ?? [];
127
- const dimensions = first.length;
128
- const result = [...first];
129
- for (let v = 1; v < vectors.length; v++) {
130
- const vec = vectors[v];
131
- if (!vec) continue;
132
- for (let i = 0; i < dimensions; i++) {
133
- const val = vec[i] ?? 0;
134
- if (val > (result[i] ?? 0)) result[i] = val;
135
- }
136
- }
137
- return result;
138
- }
139
- /**
140
- * Compute cosine similarity between two vectors.
141
- * Both vectors should be normalized for accurate results.
142
- */
143
- function cosineSimilarity(a, b) {
144
- if (a.length !== b.length) throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
145
- let dot = 0;
146
- let magnitudeA = 0;
147
- let magnitudeB = 0;
148
- for (let i = 0; i < a.length; i++) {
149
- const aVal = a[i] ?? 0;
150
- const bVal = b[i] ?? 0;
151
- dot += aVal * bVal;
152
- magnitudeA += aVal * aVal;
153
- magnitudeB += bVal * bVal;
154
- }
155
- const magnitude = Math.sqrt(magnitudeA) * Math.sqrt(magnitudeB);
156
- if (magnitude === 0) return 0;
157
- return dot / magnitude;
158
- }
159
- /**
160
- * Get the dimensions of a vector or set of vectors.
161
- */
162
- function getDimensions(vectors) {
163
- if (vectors.length === 0) return 0;
164
- const first = vectors[0];
165
- if (typeof first === "number") return vectors.length;
166
- return first?.length ?? 0;
167
- }
168
-
169
- //#endregion
170
- //#region src/embeddings/cache.ts
171
- /**
172
- * Default maximum cache entries.
173
- */
174
- const DEFAULT_MAX_ENTRIES = 1e3;
175
- /**
176
- * Default TTL in milliseconds (1 hour).
177
- */
178
- const DEFAULT_TTL_MS = 3600 * 1e3;
179
- /**
180
- * Generate a content-addressable cache key.
181
- * Key is based on content hash and embedding configuration.
182
- * Note: custom RegExp patterns are serialized by source+flags; different
183
- * constructions can yield different cache keys even if equivalent.
184
- */
185
- function generateCacheKey(params) {
186
- const hash = createHash("sha256");
187
- const fingerprint = stableStringify({
188
- providerKey: params.providerKey,
189
- model: params.model ?? "provider-default",
190
- dimensions: params.dimensions ?? "default",
191
- aggregation: params.aggregation ?? "average",
192
- input: serializeInputConfig(params.input),
193
- chunking: serializeChunkingConfig(params.chunking),
194
- safety: serializeSafetyConfig(params.safety),
195
- cacheKeySalt: params.cacheKeySalt
196
- });
197
- hash.update(fingerprint);
198
- hash.update("\0");
199
- hash.update(params.content);
200
- return hash.digest("hex");
201
- }
202
- /**
203
- * Generate a checksum for content verification.
204
- */
205
- function generateChecksum(content) {
206
- return createHash("sha256").update(content).digest("hex").slice(0, 16);
207
- }
208
- function serializeInputConfig(config) {
209
- if (!config) return void 0;
210
- return normalizeObject({
211
- type: config.type ?? "textContent",
212
- hasTransform: Boolean(config.transform),
213
- hasCustomText: Boolean(config.customText)
214
- });
215
- }
216
- function serializeChunkingConfig(config) {
217
- if (!config) return void 0;
218
- return normalizeObject({
219
- size: config.size,
220
- overlap: config.overlap,
221
- tokenizer: getTokenizerId(config.tokenizer),
222
- maxInputLength: config.maxInputLength
223
- });
224
- }
225
- function serializeSafetyConfig(config) {
226
- if (!config) return void 0;
227
- return normalizeObject({
228
- piiRedaction: serializePiiConfig(config.piiRedaction),
229
- minTextLength: config.minTextLength,
230
- maxTokens: config.maxTokens
231
- });
232
- }
233
- function serializePiiConfig(config) {
234
- if (!config) return void 0;
235
- return normalizeObject({
236
- email: config.email ?? false,
237
- phone: config.phone ?? false,
238
- creditCard: config.creditCard ?? false,
239
- ssn: config.ssn ?? false,
240
- ipAddress: config.ipAddress ?? false,
241
- customPatterns: config.customPatterns?.map((pattern) => `${pattern.source}/${pattern.flags}`)
242
- });
243
- }
244
- function getTokenizerId(tokenizer) {
245
- if (!tokenizer || tokenizer === "heuristic") return "heuristic";
246
- if (tokenizer === "tiktoken") return "tiktoken";
247
- return "custom";
248
- }
249
- function stableStringify(value) {
250
- return stringifyNormalized(normalizeValue(value));
251
- }
252
- function normalizeValue(value) {
253
- if (value === void 0) return void 0;
254
- if (value === null) return null;
255
- if (Array.isArray(value)) return value.map((entry) => normalizeValue(entry)).filter((entry) => entry !== void 0);
256
- if (typeof value === "object") return normalizeObject(value);
257
- return value;
258
- }
259
- function normalizeObject(value) {
260
- const normalized = {};
261
- for (const key of Object.keys(value).sort()) {
262
- const entry = normalizeValue(value[key]);
263
- if (entry !== void 0) normalized[key] = entry;
264
- }
265
- return normalized;
266
- }
267
- function stringifyNormalized(value) {
268
- if (value === void 0) return "undefined";
269
- if (value === null) return "null";
270
- if (typeof value === "string") return JSON.stringify(value);
271
- if (typeof value === "number" || typeof value === "boolean") return String(value);
272
- if (Array.isArray(value)) return `[${value.map((entry) => stringifyNormalized(entry)).join(",")}]`;
273
- if (typeof value === "object") {
274
- const obj = value;
275
- return `{${Object.keys(obj).sort().map((key) => `${JSON.stringify(key)}:${stringifyNormalized(obj[key])}`).join(",")}}`;
276
- }
277
- return JSON.stringify(value);
278
- }
279
- /**
280
- * In-memory LRU cache with TTL support.
281
- * Content-addressable: uses content hash as key, not URL.
282
- */
283
- var InMemoryEmbeddingCache = class {
284
- cache;
285
- maxEntries;
286
- defaultTtlMs;
287
- constructor(options) {
288
- this.cache = /* @__PURE__ */ new Map();
289
- this.maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;
290
- this.defaultTtlMs = options?.ttlMs ?? DEFAULT_TTL_MS;
291
- }
292
- async get(key) {
293
- const entry = this.cache.get(key);
294
- if (!entry) return;
295
- const now = Date.now();
296
- if (now > entry.expiresAt) {
297
- this.cache.delete(key);
298
- return;
299
- }
300
- entry.accessedAt = now;
301
- return entry.value;
302
- }
303
- async set(key, value, options) {
304
- const now = Date.now();
305
- const ttl = options?.ttlMs ?? this.defaultTtlMs;
306
- if (this.cache.size >= this.maxEntries && !this.cache.has(key)) this.evictLRU();
307
- this.cache.set(key, {
308
- value,
309
- createdAt: now,
310
- expiresAt: now + ttl,
311
- accessedAt: now
312
- });
313
- }
314
- async delete(key) {
315
- return this.cache.delete(key);
316
- }
317
- async clear() {
318
- this.cache.clear();
319
- }
320
- /**
321
- * Get cache statistics.
322
- */
323
- getStats() {
324
- const now = Date.now();
325
- let expired = 0;
326
- for (const entry of this.cache.values()) if (now > entry.expiresAt) expired++;
327
- return {
328
- size: this.cache.size,
329
- maxEntries: this.maxEntries,
330
- expired,
331
- utilization: this.cache.size / this.maxEntries
332
- };
333
- }
334
- /**
335
- * Evict expired entries.
336
- */
337
- cleanup() {
338
- const now = Date.now();
339
- let evicted = 0;
340
- for (const [key, entry] of this.cache.entries()) if (now > entry.expiresAt) {
341
- this.cache.delete(key);
342
- evicted++;
343
- }
344
- return evicted;
345
- }
346
- /**
347
- * Evict least recently used entry.
348
- */
349
- evictLRU() {
350
- let oldestKey = null;
351
- let oldestAccess = Number.POSITIVE_INFINITY;
352
- for (const [key, entry] of this.cache.entries()) if (entry.accessedAt < oldestAccess) {
353
- oldestAccess = entry.accessedAt;
354
- oldestKey = key;
355
- }
356
- if (oldestKey) this.cache.delete(oldestKey);
357
- }
358
- };
359
- /**
360
- * Default in-memory cache instance.
361
- * Optimized for moderate cache sizes (default 1000 entries).
362
- */
363
- let defaultCache = null;
364
- /**
365
- * Get or create the default cache instance.
366
- */
367
- function getDefaultCache() {
368
- if (!defaultCache) defaultCache = new InMemoryEmbeddingCache();
369
- return defaultCache;
370
- }
371
-
372
- //#endregion
373
- //#region src/embeddings/chunking.ts
374
- /**
375
- * Default chunk size in tokens.
376
- */
377
- const DEFAULT_CHUNK_SIZE$1 = 500;
378
- /**
379
- * Default overlap in tokens.
380
- */
381
- const DEFAULT_OVERLAP = 50;
382
- /**
383
- * Default maximum input length in characters.
384
- */
385
- const DEFAULT_MAX_INPUT_LENGTH = 1e5;
386
- /**
387
- * Heuristic token counting: approximately 4 characters per token.
388
- * This is a reasonable approximation for English text.
389
- */
390
- function heuristicTokenCount(text) {
391
- return Math.ceil(text.length / 4);
392
- }
393
- /**
394
- * Convert token count to approximate character count.
395
- */
396
- function tokensToChars(tokens) {
397
- return tokens * 4;
398
- }
399
- /**
400
- * Create a tokenizer function based on configuration.
401
- */
402
- function createTokenizer(config) {
403
- if (!config || config === "heuristic") return heuristicTokenCount;
404
- if (config === "tiktoken") return heuristicTokenCount;
405
- return config;
406
- }
407
- /**
408
- * Find a natural break point in text (sentence or word boundary).
409
- * Prefers common sentence boundaries (Latin + CJK), falls back to word boundaries.
410
- */
411
- function findBreakPoint(text, targetIndex) {
412
- const searchStart = Math.max(0, targetIndex - Math.floor(targetIndex * .2));
413
- const searchEnd = Math.min(text.length, targetIndex + Math.floor(targetIndex * .2));
414
- const searchText = text.slice(searchStart, searchEnd);
415
- const sentenceMatch = /[.!?。!?]\s*/g;
416
- let lastSentenceEnd = -1;
417
- for (const match of searchText.matchAll(sentenceMatch)) {
418
- const absolutePos = searchStart + match.index + match[0].length;
419
- if (absolutePos <= targetIndex) lastSentenceEnd = absolutePos;
420
- }
421
- if (lastSentenceEnd !== -1) return lastSentenceEnd;
422
- const wordBoundary = text.lastIndexOf(" ", targetIndex);
423
- if (wordBoundary > searchStart) return wordBoundary + 1;
424
- return targetIndex;
425
- }
426
- /**
427
- * Split text into overlapping chunks optimized for embedding.
428
- * Respects sentence boundaries when possible.
429
- */
430
- function chunkText(text, config) {
431
- const chunkSize = config?.size ?? DEFAULT_CHUNK_SIZE$1;
432
- const rawOverlap = config?.overlap ?? DEFAULT_OVERLAP;
433
- const safeOverlap = Math.max(0, rawOverlap);
434
- const overlap = Math.min(safeOverlap, Math.max(0, chunkSize - 1));
435
- const maxInputLength = config?.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH;
436
- const tokenizer = createTokenizer(config?.tokenizer);
437
- const normalizedText = (text.length > maxInputLength ? text.slice(0, maxInputLength) : text).replace(/\s+/g, " ").trim();
438
- if (!normalizedText) return [];
439
- const totalTokens = tokenizer(normalizedText);
440
- if (totalTokens <= chunkSize) return [{
441
- text: normalizedText,
442
- startIndex: 0,
443
- endIndex: normalizedText.length,
444
- tokens: totalTokens
445
- }];
446
- const chunks = [];
447
- const chunkSizeChars = tokensToChars(chunkSize);
448
- const overlapChars = tokensToChars(overlap);
449
- let startIndex = 0;
450
- while (startIndex < normalizedText.length) {
451
- const targetEnd = Math.min(startIndex + chunkSizeChars, normalizedText.length);
452
- const endIndex = targetEnd < normalizedText.length ? findBreakPoint(normalizedText, targetEnd) : targetEnd;
453
- const chunkText$1 = normalizedText.slice(startIndex, endIndex).trim();
454
- if (chunkText$1) chunks.push({
455
- text: chunkText$1,
456
- startIndex,
457
- endIndex,
458
- tokens: tokenizer(chunkText$1)
459
- });
460
- if (endIndex >= normalizedText.length) break;
461
- const nextStart = endIndex - overlapChars;
462
- startIndex = Math.max(nextStart, startIndex + 1);
463
- if (startIndex < normalizedText.length) {
464
- const spaceIndex = normalizedText.indexOf(" ", startIndex);
465
- if (spaceIndex !== -1 && spaceIndex < startIndex + overlapChars) startIndex = spaceIndex + 1;
466
- }
467
- }
468
- return chunks;
469
- }
470
- /**
471
- * Estimate total tokens for a text without chunking.
472
- */
473
- function estimateTokens(text, tokenizer) {
474
- return createTokenizer(tokenizer)(text);
475
- }
476
-
477
- //#endregion
478
- //#region src/embeddings/input.ts
479
- /**
480
- * Select and prepare input text for embedding based on configuration.
481
- *
482
- * @param data - Scraped data to extract input from
483
- * @param config - Input configuration
484
- * @returns Selected and prepared text, or undefined if no valid input
485
- */
486
- function selectInput(data, config) {
487
- if (config?.transform) return normalizeText(config.transform(data));
488
- if (config?.type === "custom" && config.customText) return normalizeText(config.customText);
489
- const type = config?.type ?? "textContent";
490
- switch (type) {
491
- case "textContent": return selectTextContent(data);
492
- case "title+summary": return selectTitleSummary(data);
493
- case "custom": return selectTextContent(data);
494
- default: {
495
- const _exhaustive = type;
496
- throw new Error(`Unknown input type: ${_exhaustive}`);
497
- }
498
- }
499
- }
500
- /**
501
- * Select textContent as input.
502
- */
503
- function selectTextContent(data) {
504
- if (data.textContent) return normalizeText(data.textContent);
505
- if (data.content) return normalizeText(stripMarkdown(data.content));
506
- if (data.excerpt) return normalizeText(data.excerpt);
507
- if (data.description) return normalizeText(data.description);
508
- }
509
- /**
510
- * Select title + summary (or fallbacks) as input.
511
- * Optimized for semantic search and classification.
512
- */
513
- function selectTitleSummary(data) {
514
- const parts = [];
515
- if (data.title) parts.push(data.title);
516
- if (data.summary) parts.push(data.summary);
517
- else if (data.excerpt) parts.push(data.excerpt);
518
- else if (data.description) parts.push(data.description);
519
- if (parts.length === 0) return;
520
- return normalizeText(parts.join("\n\n"));
521
- }
522
- /**
523
- * Normalize text for embedding:
524
- * - Collapse whitespace
525
- * - Trim leading/trailing whitespace
526
- * - Remove control characters
527
- */
528
- function normalizeText(text) {
529
- if (!text) return "";
530
- return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").split("\n").map((line) => line.trim()).join("\n").trim();
531
- }
532
- /**
533
- * Basic markdown stripping for when we need plain text from content.
534
- * Not comprehensive, but handles common cases.
535
- */
536
- function stripMarkdown(markdown) {
537
- return markdown.replace(/```[\s\S]*?```/g, "").replace(/`[^`]+`/g, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1").replace(/^#{1,6}\s+/gm, "").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\*([^*]+)\*/g, "$1").replace(/__([^_]+)__/g, "$1").replace(/_([^_]+)_/g, "$1").replace(/^>\s+/gm, "").replace(/^[-*_]{3,}$/gm, "").replace(/^[\s]*[-*+]\s+/gm, "").replace(/^[\s]*\d+\.\s+/gm, "");
538
- }
539
- /**
540
- * Check if the selected input meets minimum requirements.
541
- */
542
- function validateInput(text, minLength = 10) {
543
- if (!text) return {
544
- valid: false,
545
- reason: "No input text available"
546
- };
547
- if (text.length < minLength) return {
548
- valid: false,
549
- reason: `Input too short (${text.length} < ${minLength} characters)`
550
- };
551
- const wordCount = text.split(/\s+/).filter((w) => w.length > 1).length;
552
- if (wordCount < 3) return {
553
- valid: false,
554
- reason: `Input has too few words (${wordCount} < 3)`
555
- };
556
- return {
557
- valid: true,
558
- text,
559
- wordCount,
560
- charCount: text.length
561
- };
562
- }
563
-
564
- //#endregion
565
- //#region src/embeddings/providers/base.ts
566
- /**
567
- * Generate a stable cache key identifier for provider configuration.
568
- */
569
- function getProviderCacheKey(config) {
570
- switch (config.type) {
571
- case "http": return `http:${config.config.baseUrl.replace(/\/$/, "")}:${config.config.model}`;
572
- case "custom": return `custom:${config.provider.name}`;
573
- default: {
574
- const _exhaustive = config;
575
- return String(_exhaustive);
576
- }
577
- }
578
- }
579
-
580
- //#endregion
581
- //#region src/embeddings/providers/http.ts
582
- /**
583
- * HTTP-based Embedding Provider using native fetch.
584
- * Provides a unified interface for any REST-based embedding API.
585
- */
586
- /**
587
- * HTTP-based embedding provider.
588
- * Works with any REST API using native fetch.
589
- */
590
- var HttpEmbeddingProvider = class extends BaseHttpProvider {
591
- name = "http-embedding";
592
- requestBuilder;
593
- responseMapper;
594
- constructor(config) {
595
- super(config);
596
- this.requestBuilder = config.requestBuilder ?? ((texts, model) => ({
597
- input: texts,
598
- model
599
- }));
600
- this.responseMapper = config.responseMapper ?? ((response) => {
601
- const resp = response;
602
- if (Array.isArray(resp.data)) return resp.data.map((item) => item.embedding);
603
- if (Array.isArray(resp.embeddings)) return resp.embeddings;
604
- if (Array.isArray(resp.embedding)) return [resp.embedding];
605
- if (Array.isArray(response)) return response;
606
- throw new ScrapeError("Unable to parse embedding response. Provide a custom responseMapper.", "VALIDATION_ERROR");
607
- });
608
- }
609
- /**
610
- * Generate embeddings for one or more texts.
611
- */
612
- async embed(texts, options) {
613
- const model = options.model || this.model;
614
- const body = this.requestBuilder(texts, model);
615
- const { data } = await this.fetch(this.baseUrl, {
616
- body,
617
- signal: options.signal
618
- });
619
- const embeddings = this.responseMapper(data);
620
- if (embeddings.length !== texts.length) throw new ScrapeError(`Embedding count mismatch: expected ${texts.length}, got ${embeddings.length}`, "VALIDATION_ERROR");
621
- return { embeddings };
622
- }
623
- };
624
- /**
625
- * Create a generic HTTP embedding provider.
626
- */
627
- function createHttpEmbedding(config) {
628
- return new HttpEmbeddingProvider(config);
629
- }
630
-
631
- //#endregion
632
- //#region src/embeddings/providers/presets.ts
633
- /**
634
- * Create an OpenAI embedding provider.
635
- *
636
- * @example
637
- * ```ts
638
- * const provider = createOpenAIEmbedding({ apiKey: 'sk-...' });
639
- * const { embeddings } = await provider.embed(['Hello'], { model: 'text-embedding-3-small' });
640
- * ```
641
- */
642
- function createOpenAIEmbedding(options) {
643
- const apiKey = options?.apiKey ?? process.env.OPENAI_API_KEY;
644
- if (!apiKey) throw new Error("OpenAI API key required. Set OPENAI_API_KEY env var or pass apiKey option.");
645
- const headers = { Authorization: `Bearer ${apiKey}` };
646
- if (options?.organization) headers["OpenAI-Organization"] = options.organization;
647
- return new HttpEmbeddingProvider({
648
- baseUrl: options?.baseUrl ?? "https://api.openai.com/v1/embeddings",
649
- model: options?.model ?? "text-embedding-3-small",
650
- headers,
651
- requestBuilder: (texts, model) => ({
652
- input: texts,
653
- model
654
- }),
655
- responseMapper: (res) => res.data.map((item) => item.embedding)
656
- });
657
- }
658
- /**
659
- * Create an Azure OpenAI embedding provider.
660
- *
661
- * @example
662
- * ```ts
663
- * const provider = createAzureEmbedding({
664
- * endpoint: 'https://my-resource.openai.azure.com',
665
- * deploymentName: 'text-embedding-ada-002',
666
- * apiVersion: '2023-05-15',
667
- * });
668
- * ```
669
- */
670
- function createAzureEmbedding(options) {
671
- const apiKey = options.apiKey ?? process.env.AZURE_OPENAI_API_KEY;
672
- if (!apiKey) throw new Error("Azure OpenAI API key required. Set AZURE_OPENAI_API_KEY env var or pass apiKey option.");
673
- return new HttpEmbeddingProvider({
674
- baseUrl: `${options.endpoint.replace(/\/$/, "")}/openai/deployments/${options.deploymentName}/embeddings?api-version=${options.apiVersion}`,
675
- model: options.deploymentName,
676
- headers: { "api-key": apiKey },
677
- requestBuilder: (texts) => ({ input: texts }),
678
- responseMapper: (res) => res.data.map((item) => item.embedding)
679
- });
680
- }
681
- /**
682
- * Create an Ollama embedding provider for local models.
683
- *
684
- * LIMITATION: Ollama's /api/embeddings endpoint processes one text at a time,
685
- * not batches. When multiple chunks are embedded, each chunk triggers a
686
- * separate HTTP request. This is handled transparently by the pipeline's
687
- * sequential chunk processing, but may be slower than batch-capable providers.
688
- * For high-throughput scenarios, consider using OpenAI, Cohere, or HuggingFace
689
- * which support batch embedding in a single request.
690
- *
691
- * @example
692
- * ```ts
693
- * const provider = createOllamaEmbedding({ model: 'nomic-embed-text' });
694
- * ```
695
- */
696
- function createOllamaEmbedding(options) {
697
- return new HttpEmbeddingProvider({
698
- baseUrl: options?.baseUrl ?? "http://localhost:11434/api/embeddings",
699
- model: options?.model ?? "nomic-embed-text",
700
- requireHttps: false,
701
- allowPrivate: true,
702
- requestBuilder: (texts, model) => ({
703
- model,
704
- prompt: texts[0]
705
- }),
706
- responseMapper: (res) => [res.embedding]
707
- });
708
- }
709
- /**
710
- * Create a HuggingFace Inference API embedding provider.
711
- *
712
- * @example
713
- * ```ts
714
- * const provider = createHuggingFaceEmbedding({
715
- * model: 'sentence-transformers/all-MiniLM-L6-v2',
716
- * });
717
- * ```
718
- */
719
- function createHuggingFaceEmbedding(options) {
720
- const apiKey = options.apiKey ?? process.env.HF_TOKEN ?? process.env.HUGGINGFACE_API_KEY;
721
- const headers = {};
722
- if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
723
- return new HttpEmbeddingProvider({
724
- baseUrl: `https://api-inference.huggingface.co/models/${options.model}`,
725
- model: options.model,
726
- headers,
727
- requestBuilder: (texts) => ({ inputs: texts }),
728
- responseMapper: (response) => {
729
- if (Array.isArray(response)) {
730
- if (Array.isArray(response[0]) && typeof response[0][0] === "number") return response;
731
- return [response];
732
- }
733
- throw new Error("Unexpected HuggingFace response format");
734
- }
735
- });
736
- }
737
- /**
738
- * Create a local Transformers.js embedding provider.
739
- * Uses dependency injection - user provides the imported transformers module.
740
- *
741
- * @example
742
- * ```typescript
743
- * import * as transformers from '@huggingface/transformers';
744
- * import { createTransformersEmbedding } from 'scrapex/embeddings';
745
- *
746
- * const provider = createTransformersEmbedding(transformers, {
747
- * model: 'Xenova/all-MiniLM-L6-v2',
748
- * });
749
- * ```
750
- *
751
- * Required Node.js dependencies:
752
- * ```
753
- * npm install @huggingface/transformers onnxruntime-node
754
- * ```
755
- */
756
- function createTransformersEmbedding(transformers, options) {
757
- let pipeline = null;
758
- let currentModel = null;
759
- const config = {
760
- model: options?.model ?? "Xenova/all-MiniLM-L6-v2",
761
- quantized: options?.quantized ?? true,
762
- pooling: options?.pooling ?? "mean",
763
- normalize: options?.normalize ?? true
764
- };
765
- return {
766
- name: "transformers",
767
- async embed(texts, request) {
768
- const model = request.model || config.model;
769
- if (!pipeline || currentModel !== model) {
770
- const cacheDir = options?.cacheDir;
771
- const env = transformers.env;
772
- const priorCacheDir = env?.cacheDir;
773
- if (cacheDir && env) env.cacheDir = cacheDir;
774
- try {
775
- pipeline = await transformers.pipeline("feature-extraction", model, { quantized: config.quantized });
776
- } finally {
777
- if (cacheDir && env) if (priorCacheDir === void 0) delete env.cacheDir;
778
- else env.cacheDir = priorCacheDir;
779
- }
780
- currentModel = model;
781
- }
782
- const embeddings = [];
783
- for (const text of texts) {
784
- const output = await pipeline(text, {
785
- pooling: config.pooling,
786
- normalize: config.normalize
787
- });
788
- embeddings.push(Array.from(output.data));
789
- }
790
- return { embeddings };
791
- }
792
- };
793
- }
794
- /** Recommended models for Transformers.js */
795
- const TRANSFORMERS_MODELS = {
796
- DEFAULT: "Xenova/all-MiniLM-L6-v2",
797
- QUALITY: "Xenova/all-mpnet-base-v2",
798
- RETRIEVAL: "Xenova/bge-small-en-v1.5",
799
- MULTILINGUAL: "Xenova/multilingual-e5-small"
800
- };
801
-
802
- //#endregion
803
- //#region src/embeddings/providers/index.ts
804
- /**
805
- * Create an embedding provider from configuration.
806
- * This is the main factory function for creating providers.
807
- */
808
- function createEmbeddingProvider(config) {
809
- switch (config.type) {
810
- case "http": return createHttpEmbedding(config.config);
811
- case "custom": return config.provider;
812
- default: throw new ScrapeError(`Unknown embedding provider type: ${config.type}`, "VALIDATION_ERROR");
813
- }
814
- }
815
-
816
- //#endregion
817
- //#region src/embeddings/safety.ts
818
- /**
819
- * PII redaction patterns with high precision to minimize false positives.
820
- * Patterns are designed to match common formats while avoiding over-matching.
821
- */
822
- const EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
823
- const PHONE_PATTERN = /(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/g;
824
- const CREDIT_CARD_PATTERN = /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|(?:[0-9]{4}[-\s]){3}[0-9]{4}|[0-9]{13,19})\b/g;
825
- const SSN_PATTERN = /\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b/g;
826
- const IPV4_PATTERN = /\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g;
827
- const REDACTED = "[REDACTED]";
828
- /**
829
- * Create a redaction function based on configuration.
830
- * Returns a function that applies all configured PII patterns.
831
- */
832
- function createPiiRedactor(config) {
833
- const patterns = [];
834
- if (config.creditCard) patterns.push({
835
- name: "creditCard",
836
- pattern: CREDIT_CARD_PATTERN
837
- });
838
- if (config.email) patterns.push({
839
- name: "email",
840
- pattern: EMAIL_PATTERN
841
- });
842
- if (config.phone) patterns.push({
843
- name: "phone",
844
- pattern: PHONE_PATTERN
845
- });
846
- if (config.ssn) patterns.push({
847
- name: "ssn",
848
- pattern: SSN_PATTERN
849
- });
850
- if (config.ipAddress) patterns.push({
851
- name: "ipAddress",
852
- pattern: IPV4_PATTERN
853
- });
854
- if (config.customPatterns) for (let i = 0; i < config.customPatterns.length; i++) {
855
- const customPattern = config.customPatterns[i];
856
- if (customPattern) patterns.push({
857
- name: `custom_${i}`,
858
- pattern: customPattern
859
- });
860
- }
861
- return (text) => {
862
- let redactedText = text;
863
- let totalRedactions = 0;
864
- const redactionsByType = {};
865
- for (const { name, pattern } of patterns) {
866
- pattern.lastIndex = 0;
867
- const matchCount = text.match(pattern)?.length ?? 0;
868
- if (matchCount > 0) {
869
- redactedText = redactedText.replace(pattern, REDACTED);
870
- totalRedactions += matchCount;
871
- redactionsByType[name] = (redactionsByType[name] ?? 0) + matchCount;
872
- }
873
- }
874
- return {
875
- text: redactedText,
876
- redacted: totalRedactions > 0,
877
- redactionCount: totalRedactions,
878
- redactionsByType
879
- };
880
- };
881
- }
882
- /**
883
- * Simple redaction that applies all default patterns.
884
- * Use createPiiRedactor() for fine-grained control.
885
- */
886
- function redactPii(text) {
887
- return createPiiRedactor({
888
- email: true,
889
- phone: true,
890
- creditCard: true,
891
- ssn: true,
892
- ipAddress: true
893
- })(text);
894
- }
895
-
896
- //#endregion
897
- //#region src/embeddings/pipeline.ts
898
- const DEFAULT_CHUNK_SIZE = 500;
899
- /**
900
- * Get the effective model for embedding.
901
- * Prioritizes: explicit options.model > provider config model
902
- */
903
- function getEffectiveModel(providerConfig, explicitModel) {
904
- if (explicitModel) return explicitModel;
905
- if (providerConfig.type === "http") return providerConfig.config.model;
906
- }
907
- /**
908
- * Generate embeddings for scraped data.
909
- * This is the main entry point for the embedding pipeline.
910
- */
911
- async function generateEmbeddings(data, options) {
912
- const startTime = Date.now();
913
- try {
914
- const provider = createEmbeddingProvider(options.provider);
915
- const model = getEffectiveModel(options.provider, options.model);
916
- const validation = validateInput(selectInput(data, options.input), options.safety?.minTextLength ?? 10);
917
- if (!validation.valid) return createSkippedResult(validation.reason, { model });
918
- const originalInput = validation.text;
919
- let inputText = validation.text;
920
- let piiRedacted = false;
921
- if (options.safety?.piiRedaction) {
922
- const redactionResult = createPiiRedactor(options.safety.piiRedaction)(inputText);
923
- inputText = redactionResult.text;
924
- piiRedacted = redactionResult.redacted;
925
- }
926
- const effectiveChunking = applyMaxTokensToChunking(options.chunking, options.safety?.maxTokens);
927
- const cacheKey = generateCacheKey({
928
- providerKey: getProviderCacheKey(options.provider),
929
- model,
930
- dimensions: options.output?.dimensions,
931
- aggregation: options.output?.aggregation,
932
- input: options.input,
933
- chunking: effectiveChunking,
934
- safety: options.safety,
935
- cacheKeySalt: options.cache?.cacheKeySalt,
936
- content: inputText
937
- });
938
- const cache = options.cache?.store ?? getDefaultCache();
939
- const cachedResult = await cache.get(cacheKey);
940
- if (cachedResult && cachedResult.status === "success") {
941
- if (options.onMetrics) options.onMetrics({
942
- provider: provider.name,
943
- model,
944
- inputTokens: estimateTokens(inputText),
945
- outputDimensions: getDimensions(cachedResult.aggregation === "all" ? cachedResult.vectors : cachedResult.vector),
946
- chunks: cachedResult.source.chunks,
947
- latencyMs: Date.now() - startTime,
948
- cached: true,
949
- retries: 0,
950
- piiRedacted
951
- });
952
- return {
953
- ...cachedResult,
954
- source: {
955
- ...cachedResult.source,
956
- cached: true
957
- }
958
- };
959
- }
960
- const chunks = chunkText(inputText, effectiveChunking);
961
- const callbackChunks = options.onChunk && options.safety?.allowSensitiveCallbacks ? chunkText(originalInput, effectiveChunking) : null;
962
- if (chunks.length === 0) return createSkippedResult("No content after chunking", { model });
963
- const sharedState = options.resilience?.state;
964
- const rateLimiter = sharedState?.rateLimiter ?? (options.resilience?.rateLimit ? new RateLimiter(options.resilience.rateLimit) : null);
965
- const circuitBreaker = sharedState?.circuitBreaker ?? (options.resilience?.circuitBreaker ? new CircuitBreaker(options.resilience.circuitBreaker) : null);
966
- const concurrency = options.resilience?.concurrency ?? 1;
967
- const semaphore = sharedState?.semaphore ?? new Semaphore(concurrency);
968
- const embeddings = [];
969
- let totalTokens = 0;
970
- let retryCount = 0;
971
- for (let i = 0; i < chunks.length; i++) {
972
- const chunk = chunks[i];
973
- if (!chunk) continue;
974
- if (rateLimiter) await rateLimiter.acquire();
975
- if (circuitBreaker?.isOpen()) return createSkippedResult("Circuit breaker is open", {
976
- model,
977
- chunks: i
978
- });
979
- await semaphore.execute(async () => {
980
- const { result: result$1 } = await withResilience(async (signal) => {
981
- return provider.embed([chunk.text], {
982
- model,
983
- dimensions: options.output?.dimensions,
984
- signal
985
- });
986
- }, options.resilience, {
987
- circuitBreaker: circuitBreaker ?? void 0,
988
- rateLimiter: void 0,
989
- semaphore: void 0
990
- }, { onRetry: () => {
991
- retryCount++;
992
- } });
993
- if (result$1.usage) totalTokens += result$1.usage.totalTokens;
994
- else totalTokens += chunk.tokens;
995
- const embedding = result$1.embeddings[0];
996
- if (embedding) {
997
- embeddings.push(embedding);
998
- if (options.onChunk) {
999
- const callbackText = callbackChunks?.[i]?.text ?? chunk.text;
1000
- options.onChunk(callbackText, embedding);
1001
- }
1002
- }
1003
- });
1004
- }
1005
- const aggregation = options.output?.aggregation ?? "average";
1006
- const aggregated = aggregateVectors(embeddings, aggregation);
1007
- const source = {
1008
- model,
1009
- chunks: chunks.length,
1010
- tokens: totalTokens || estimateTokens(inputText),
1011
- checksum: generateChecksum(inputText),
1012
- cached: false,
1013
- latencyMs: Date.now() - startTime
1014
- };
1015
- let result;
1016
- if (aggregated.type === "single") result = {
1017
- status: "success",
1018
- aggregation,
1019
- vector: aggregated.vector,
1020
- source
1021
- };
1022
- else result = {
1023
- status: "success",
1024
- aggregation: "all",
1025
- vectors: aggregated.vectors,
1026
- source
1027
- };
1028
- await cache.set(cacheKey, result, { ttlMs: options.cache?.ttlMs });
1029
- if (options.onMetrics) {
1030
- const metrics = {
1031
- provider: provider.name,
1032
- model,
1033
- inputTokens: source.tokens,
1034
- outputDimensions: aggregated.dimensions,
1035
- chunks: chunks.length,
1036
- latencyMs: source.latencyMs,
1037
- cached: false,
1038
- retries: retryCount,
1039
- piiRedacted
1040
- };
1041
- options.onMetrics(metrics);
1042
- }
1043
- return result;
1044
- } catch (error) {
1045
- const reason = error instanceof Error ? error.message : String(error);
1046
- if (error instanceof ScrapeError && ["INVALID_URL", "BLOCKED"].includes(error.code)) throw error;
1047
- return createSkippedResult(reason, { latencyMs: Date.now() - startTime });
1048
- }
1049
- }
1050
- function applyMaxTokensToChunking(chunking, maxTokens) {
1051
- if (!maxTokens || maxTokens <= 0) return chunking;
1052
- const baseSize = chunking?.size ?? DEFAULT_CHUNK_SIZE;
1053
- const baseOverlap = chunking?.overlap ?? 50;
1054
- const clampedSize = Math.min(baseSize, maxTokens);
1055
- const clampedOverlap = Math.min(baseOverlap, Math.max(0, clampedSize - 1));
1056
- return {
1057
- ...chunking,
1058
- size: clampedSize,
1059
- overlap: clampedOverlap
1060
- };
1061
- }
1062
- /**
1063
- * Embed arbitrary text directly.
1064
- * Standalone function for embedding text outside of scrape().
1065
- */
1066
- async function embed(text, options) {
1067
- return generateEmbeddings({ textContent: text }, {
1068
- ...options,
1069
- input: {
1070
- ...options.input,
1071
- type: "textContent"
1072
- }
1073
- });
1074
- }
1075
- /**
1076
- * Embed from existing ScrapedData.
1077
- * Useful when you've already scraped and want to add embeddings later.
1078
- */
1079
- async function embedScrapedData(data, options) {
1080
- return generateEmbeddings(data, options);
1081
- }
1082
- /**
1083
- * Create a skipped result with reason.
1084
- */
1085
- function createSkippedResult(reason, partialSource) {
1086
- return {
1087
- status: "skipped",
1088
- reason,
1089
- source: partialSource ?? {}
1090
- };
1091
- }
1092
-
1093
58
  //#endregion
1094
59
  //#region src/extractors/content.ts
1095
60
  const turndown = new TurndownService({