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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import { parseMarkdown } from "../../../lib/html-to-markdown";
import { Meta } from "..";
import { Document } from "../../../controllers/v2/types";
import { htmlTransform } from "../lib/removeUnwantedElements";
import { extractLinks } from "../lib/extractLinks";
import { extractImages } from "../lib/extractImages";
import { extractMetadata } from "../lib/extractMetadata";
import {
  performLLMExtract,
  performSummary,
  performCleanContent,
} from "./llmExtract";
import { performQuery } from "./query";
import { uploadScreenshot } from "./uploadScreenshot";
import { removeBase64Images } from "./removeBase64Images";
import { performAgent } from "./agent";
import { performAttributes } from "./performAttributes";

import { deriveDiff } from "./diff";
import { fetchAudio } from "./audio";
import { fetchVideo } from "./video";
import { useIndex, useSearchIndex } from "../../../services/index";
import { sendDocumentToIndex } from "../engines/index/index";
import { sendDocumentToSearchIndex } from "./sendToSearchIndex";
import { hasFormatOfType } from "../../../lib/format-utils";
import { brandingTransformer } from "../../../lib/branding/transformer";
import { indexerQueue } from "../../../services/indexing/indexer-queue";
import { config } from "../../../config";

type Transformer = (
  meta: Meta,
  document: Document,
) => Document | Promise<Document>;

async function deriveMetadataFromRawHTML(
  meta: Meta,
  document: Document,
): Promise<Document> {
  if (document.rawHtml === undefined) {
    throw new Error(
      "rawHtml is undefined -- this transformer is being called out of order",
    );
  }

  document.metadata = {
    ...(await extractMetadata(meta, document.rawHtml)),
    ...document.metadata,
  };
  return document;
}

async function deriveHTMLFromRawHTML(
  meta: Meta,
  document: Document,
): Promise<Document> {
  if (document.rawHtml === undefined) {
    throw new Error(
      "rawHtml is undefined -- this transformer is being called out of order",
    );
  }

  document.html = await htmlTransform(
    document.rawHtml,
    document.metadata.url ??
      document.metadata.sourceURL ??
      meta.rewrittenUrl ??
      meta.url,
    meta.options,
  );
  return document;
}

async function deriveMarkdownFromHTML(
  meta: Meta,
  document: Document,
): Promise<Document> {
  if (document.html === undefined) {
    throw new Error(
      "html is undefined -- this transformer is being called out of order",
    );
  }

  // Only derive markdown if markdown format is requested or if formats that require markdown are requested:
  // - changeTracking requires markdown
  // - json format requires markdown (for LLM extraction)
  // - summary format requires markdown (for summarization)
  // - question/highlights/query formats require markdown (for page-level answers)
  const hasMarkdown = hasFormatOfType(meta.options.formats, "markdown");
  const hasChangeTracking = hasFormatOfType(
    meta.options.formats,
    "changeTracking",
  );
  const hasJson = hasFormatOfType(meta.options.formats, "json");
  const hasSummary = hasFormatOfType(meta.options.formats, "summary");
  const hasQuestion = hasFormatOfType(meta.options.formats, "question");
  const hasHighlights = hasFormatOfType(meta.options.formats, "highlights");
  const hasQuery = hasFormatOfType(meta.options.formats, "query");
  if (
    !hasMarkdown &&
    !hasChangeTracking &&
    !hasJson &&
    !hasSummary &&
    !hasQuestion &&
    !hasHighlights &&
    !hasQuery &&
    !meta.options.onlyCleanContent
  ) {
    return document;
  }

  // Skip markdown derivation if a postprocessor already set it
  if (document.metadata.postprocessorsUsed?.length && document.markdown) {
    meta.logger.debug(
      "Skipping markdown derivation - postprocessor already set markdown",
      { postprocessorsUsed: document.metadata.postprocessorsUsed },
    );
    return document;
  }

  if (document.metadata.contentType?.includes("application/json")) {
    if (document.rawHtml === undefined) {
      throw new Error(
        "rawHtml is undefined -- this transformer is being called out of order",
      );
    }

    document.markdown = "```json\n" + document.rawHtml + "\n```";
    return document;
  }

  // Use scrape ID or crawl ID as request_id for tracing
  const requestId = meta.id || meta.internalOptions.crawlId;
  document.markdown = await parseMarkdown(document.html, {
    logger: meta.logger,
    requestId,
    zeroDataRetention: meta.internalOptions.zeroDataRetention,
  });

  if (
    meta.options.onlyMainContent === true &&
    (!document.markdown || document.markdown.trim().length === 0)
  ) {
    meta.logger.info(
      "Main content extraction resulted in empty markdown, falling back to full content extraction",
    );

    const fallbackMeta = {
      ...meta,
      options: {
        ...meta.options,
        onlyMainContent: false,
      },
    };

    document = await deriveHTMLFromRawHTML(fallbackMeta, document);
    document.markdown = await parseMarkdown(document.html, {
      logger: meta.logger,
      requestId,
      zeroDataRetention: meta.internalOptions.zeroDataRetention,
    });

    meta.logger.info("Fallback to full content extraction completed", {
      markdownLength: document.markdown?.length || 0,
    });
  }

  return document;
}

async function deriveLinksFromHTML(
  meta: Meta,
  document: Document,
): Promise<Document> {
  if (document.html === undefined) {
    throw new Error(
      "html is undefined -- this transformer is being called out of order",
    );
  }

  const rate = config.INDEXER_TRAFFIC_SHARE
    ? Math.max(0, Math.min(1, Number(config.INDEXER_TRAFFIC_SHARE)))
    : 0;

  const shouldForwardTraffic =
    rate > 0 && Math.random() <= rate && !!config.INDEXER_RABBITMQ_URL;

  const forwardToIndexer =
    !meta.internalOptions.isParse &&
    !!meta.internalOptions.teamId &&
    !meta.internalOptions.teamId?.includes("robots-txt") &&
    !meta.internalOptions.teamId?.includes("sitemap") &&
    shouldForwardTraffic;

  const requiresLinks = !!hasFormatOfType(meta.options.formats, "links");

  if (!forwardToIndexer && !requiresLinks) {
    return document;
  }

  document.links = await extractLinks(
    document.html,
    document.metadata.url ??
      document.metadata.sourceURL ??
      meta.rewrittenUrl ??
      meta.url,
  );

  if (forwardToIndexer) {
    try {
      let linksDeduped: Set<string> = new Set();
      if (!!document.links) {
        linksDeduped = new Set([...document.links]);
      }

      indexerQueue
        .sendToWorker({
          id: meta.id,
          type: "links",
          discovery_url:
            document.metadata.url ??
            document.metadata.sourceURL ??
            meta.rewrittenUrl ??
            meta.url,
          urls: [...linksDeduped],
        })
        .catch(error => {
          meta.logger.error("Failed to queue links for indexing", {
            error: (error as Error)?.message,
            url: meta.url,
          });
        });
    } catch (error) {
      meta.logger.error("Failed to queue links for indexing", {
        error: (error as Error)?.message,
        url: meta.url,
      });
    }
  }

  if (!requiresLinks) {
    delete document.links;
  }

  return document;
}

async function deriveImagesFromHTML(
  meta: Meta,
  document: Document,
): Promise<Document> {
  // Only derive if the formats has images
  if (hasFormatOfType(meta.options.formats, "images")) {
    if (document.html === undefined) {
      throw new Error(
        "html is undefined -- this transformer is being called out of order",
      );
    }

    document.images = await extractImages(
      document.html,
      document.metadata.url ??
        document.metadata.sourceURL ??
        meta.rewrittenUrl ??
        meta.url,
    );
  }

  return document;
}

async function deriveBrandingFromActions(
  meta: Meta,
  document: Document,
): Promise<Document> {
  const hasBranding = hasFormatOfType(meta.options.formats, "branding");

  if (!hasBranding) {
    return document;
  }

  if (document.branding !== undefined) {
    return document;
  }

  /**
   * Find the branding return in the actions javascript returns
   * @see src/scraper/scrapeURL/engines/fire-engine/scripts/branding.js
   */
  const brandingReturnIndex = document.actions?.javascriptReturns?.findIndex(
    x => x.type === "object" && "branding" in (x.value as any),
  );

  if (brandingReturnIndex === -1 || brandingReturnIndex === undefined) {
    return document;
  }

  // cast as any since this is js return, we might need to validate this
  const javascriptReturn = document.actions!.javascriptReturns![
    brandingReturnIndex
  ].value as any;

  const rawBranding = javascriptReturn?.branding;

  document.actions!.javascriptReturns!.splice(brandingReturnIndex, 1);

  document.branding = await brandingTransformer(meta, document, rawBranding);

  return document;
}

function coerceFieldsToFormats(meta: Meta, document: Document): Document {
  const hasMarkdown = hasFormatOfType(meta.options.formats, "markdown");
  const hasRawHtml = hasFormatOfType(meta.options.formats, "rawHtml");
  const hasHtml = hasFormatOfType(meta.options.formats, "html");
  const hasLinks = hasFormatOfType(meta.options.formats, "links");
  const hasImages = hasFormatOfType(meta.options.formats, "images");
  const hasChangeTracking = hasFormatOfType(
    meta.options.formats,
    "changeTracking",
  );
  const hasJson = hasFormatOfType(meta.options.formats, "json");
  const hasScreenshot = hasFormatOfType(meta.options.formats, "screenshot");
  const hasSummary = hasFormatOfType(meta.options.formats, "summary");
  const hasBranding = hasFormatOfType(meta.options.formats, "branding");
  const hasQuestionFormat = hasFormatOfType(meta.options.formats, "question");
  const hasHighlightsFormat = hasFormatOfType(
    meta.options.formats,
    "highlights",
  );
  const hasLegacyQueryFormat = hasFormatOfType(meta.options.formats, "query");
  const hasAnswerFormat = hasQuestionFormat || hasLegacyQueryFormat;

  if (!hasMarkdown && document.markdown !== undefined) {
    delete document.markdown;
  } else if (hasMarkdown && document.markdown === undefined) {
    meta.logger.warn(
      "Request had format: markdown, but there was no markdown field in the result.",
    );
  }

  if (!hasRawHtml && document.rawHtml !== undefined) {
    delete document.rawHtml;
  } else if (hasRawHtml && document.rawHtml === undefined) {
    meta.logger.warn(
      "Request had format: rawHtml, but there was no rawHtml field in the result.",
    );
  }

  if (!hasHtml && document.html !== undefined) {
    delete document.html;
  } else if (hasHtml && document.html === undefined) {
    meta.logger.warn(
      "Request had format: html, but there was no html field in the result.",
    );
  }

  if (!hasScreenshot && document.screenshot !== undefined) {
    meta.logger.warn(
      "Removed screenshot from Document because it wasn't in formats -- this is very wasteful and indicates a bug.",
    );
    delete document.screenshot;
  } else if (hasScreenshot && document.screenshot === undefined) {
    meta.logger.warn(
      "Request had format: screenshot / screenshot@fullPage, but there was no screenshot field in the result.",
    );
  }

  if (!hasLinks && document.links !== undefined) {
    meta.logger.warn(
      "Removed links from Document because it wasn't in formats -- this is wasteful and indicates a bug.",
    );
    delete document.links;
  } else if (hasLinks && document.links === undefined) {
    meta.logger.warn(
      "Request had format: links, but there was no links field in the result.",
    );
  }

  if (!hasImages && document.images !== undefined) {
    meta.logger.warn(
      "Removed images from Document because it wasn't in formats -- this is wasteful and indicates a bug.",
      { hasImages, hasImagesField: document.images !== undefined },
    );
    delete document.images;
  } else if (hasImages && document.images === undefined) {
    meta.logger.warn(
      "Request had format: images, but there was no images field in the result.",
      { hasImages, hasImagesField: document.images !== undefined },
    );
  }

  // Handle v1 backward compatibility - don't delete fields based on v1OriginalFormat
  const shouldKeepExtract = meta.internalOptions.v1OriginalFormat === "extract";
  const shouldKeepJson = meta.internalOptions.v1OriginalFormat === "json";

  // Debug logging for v1 format investigation
  if (meta.internalOptions.v1OriginalFormat) {
    meta.logger.debug("coerceFieldsToFormats v1 format debug", {
      v1OriginalFormat: meta.internalOptions.v1OriginalFormat,
      hasJson: !!hasJson,
      shouldKeepExtract,
      shouldKeepJson,
      hasExtractField: document.extract !== undefined,
      hasJsonField: document.json !== undefined,
    });
  }

  if (
    !hasJson &&
    (document.extract !== undefined || document.json !== undefined)
  ) {
    // For v1 API, keep the field specified by v1OriginalFormat
    if (!shouldKeepExtract && document.extract !== undefined) {
      meta.logger.warn(
        "Removed extract from Document because it wasn't in formats -- this is extremely wasteful and indicates a bug.",
      );
      delete document.extract;
    }
    if (!shouldKeepJson && document.json !== undefined) {
      meta.logger.warn(
        "Removed json from Document because it wasn't in formats -- this is extremely wasteful and indicates a bug.",
      );
      delete document.json;
    }
  } else if (
    hasJson &&
    document.extract === undefined &&
    document.json === undefined
  ) {
    meta.logger.warn(
      "Request had format json, but there was no json field in the result.",
    );
  }

  if (!hasSummary && document.summary !== undefined) {
    meta.logger.warn(
      "Removed summary from Document because it wasn't in formats -- this is wasteful and indicates a bug.",
    );
    delete document.summary;
  } else if (hasSummary && document.summary === undefined) {
    meta.logger.warn(
      "Request had format summary, but there was no summary field in the result.",
    );
  }

  if (!hasAnswerFormat && document.answer !== undefined) {
    meta.logger.warn(
      "Removed answer from Document because question/query wasn't in formats -- this is wasteful and indicates a bug.",
    );
    delete document.answer;
  } else if (hasAnswerFormat && document.answer === undefined) {
    meta.logger.warn(
      "Request had format question/query, but there was no answer field in the result.",
    );
  }

  if (!hasHighlightsFormat && document.highlights !== undefined) {
    meta.logger.warn(
      "Removed highlights from Document because highlights wasn't in formats -- this is wasteful and indicates a bug.",
    );
    delete document.highlights;
  } else if (hasHighlightsFormat && document.highlights === undefined) {
    meta.logger.warn(
      "Request had format highlights, but there was no highlights field in the result.",
    );
  }

  if (!hasBranding && document.branding !== undefined) {
    meta.logger.warn(
      "Removed branding from Document because it wasn't in formats -- this indicates the engine returned unexpected data.",
    );
    delete document.branding;
  } else if (hasBranding && document.branding === undefined) {
    meta.logger.warn(
      "Request had format branding, but there was no branding field in the result.",
    );
  }

  const hasAudio = hasFormatOfType(meta.options.formats, "audio");
  if (!hasAudio && document.audio !== undefined) {
    delete document.audio;
  } else if (hasAudio && document.audio === undefined) {
    meta.logger.warn(
      "Request had format: audio, but there was no audio field in the result.",
    );
  }

  const hasVideo = hasFormatOfType(meta.options.formats, "video");
  if (!hasVideo && document.video !== undefined) {
    delete document.video;
  } else if (hasVideo && document.video === undefined) {
    meta.logger.warn(
      "Request had format: video, but there was no video field in the result.",
    );
  }

  if (!hasChangeTracking && document.changeTracking !== undefined) {
    meta.logger.warn(
      "Removed changeTracking from Document because it wasn't in formats -- this is extremely wasteful and indicates a bug.",
    );
    delete document.changeTracking;
  } else if (hasChangeTracking && document.changeTracking === undefined) {
    meta.logger.warn(
      "Request had format changeTracking, but there was no changeTracking field in the result.",
    );
  }

  if (
    document.changeTracking &&
    !hasChangeTracking?.modes?.includes("git-diff") &&
    document.changeTracking.diff !== undefined
  ) {
    meta.logger.warn(
      "Removed diff from changeTracking because git-diff mode wasn't specified in changeTrackingOptions.modes.",
    );
    delete document.changeTracking.diff;
  }

  if (
    document.changeTracking &&
    !hasChangeTracking?.modes?.includes("json") &&
    document.changeTracking.json !== undefined
  ) {
    meta.logger.warn(
      "Removed structured from changeTracking because structured mode wasn't specified in changeTrackingOptions.modes.",
    );
    delete document.changeTracking.json;
  }

  if (meta.options.actions === undefined || meta.options.actions.length === 0) {
    delete document.actions;
  } else if (document.actions) {
    // Check if all action arrays are empty
    const hasScreenshots =
      document.actions.screenshots && document.actions.screenshots.length > 0;
    const hasScrapes =
      document.actions.scrapes && document.actions.scrapes.length > 0;
    const hasJsReturns =
      document.actions.javascriptReturns &&
      document.actions.javascriptReturns.length > 0;
    const hasPdfs = document.actions.pdfs && document.actions.pdfs.length > 0;

    if (!hasScreenshots && !hasScrapes && !hasJsReturns && !hasPdfs) {
      delete document.actions;
    }
  }

  return document;
}

// TODO: allow some of these to run in parallel
const transformerStack: Transformer[] = [
  deriveHTMLFromRawHTML,
  deriveMarkdownFromHTML,
  performCleanContent,
  deriveLinksFromHTML,
  deriveImagesFromHTML,
  deriveBrandingFromActions,
  deriveMetadataFromRawHTML,
  uploadScreenshot,
  ...(useIndex ? [sendDocumentToIndex] : []),
  ...(useSearchIndex ? [sendDocumentToSearchIndex] : []), // Add to search index for real-time search
  performLLMExtract,
  performSummary,
  performQuery,
  performAttributes,
  performAgent,
  removeBase64Images,
  deriveDiff,
  fetchAudio,
  fetchVideo,
  coerceFieldsToFormats,
];

export async function executeTransformers(
  meta: Meta,
  document: Document,
): Promise<Document> {
  const executions: [string, number][] = [];

  for (const transformer of transformerStack) {
    const _meta = {
      ...meta,
      logger: meta.logger.child({
        method: "executeTransformers/" + transformer.name,
      }),
    };
    const start = Date.now();
    document = await transformer(_meta, document);
    executions.push([transformer.name, Date.now() - start]);
  }

  meta.logger.debug("Executed transformers.", { executions });

  return document;
}