@aglyn/plugins-ai 1.10.0 → 1.12.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.
Files changed (58) hide show
  1. package/package.json +17 -17
  2. package/src/lib/jobs/ai-job-import-step.d.ts +1 -1
  3. package/src/lib/jobs/ai-job-import-step.js +26 -7
  4. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  5. package/src/lib/jobs/ai-job-privacy-step.js +2 -2
  6. package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
  7. package/src/lib/jobs/ai-site-import-compile.js +27 -37
  8. package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
  9. package/src/lib/jobs/ai-site-import-look.js +20 -1
  10. package/src/lib/jobs/ai-site-import-look.js.map +1 -1
  11. package/src/lib/layout-language/ai-layout-compiler.js +7 -1
  12. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  13. package/src/lib/model/ai-credit-estimate.d.ts +15 -0
  14. package/src/lib/model/ai-credit-estimate.js +13 -0
  15. package/src/lib/model/ai-credit-estimate.js.map +1 -1
  16. package/src/lib/model/ai-site-import-fidelity.d.ts +46 -3
  17. package/src/lib/model/ai-site-import-fidelity.js +254 -62
  18. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  19. package/src/lib/model/ai-site-import-report.d.ts +7 -0
  20. package/src/lib/model/ai-site-import-report.js +17 -5
  21. package/src/lib/model/ai-site-import-report.js.map +1 -1
  22. package/src/lib/model/ai-site-import.d.ts +46 -3
  23. package/src/lib/model/ai-site-import.js +34 -11
  24. package/src/lib/model/ai-site-import.js.map +1 -1
  25. package/src/lib/model/ai-site-look.d.ts +16 -0
  26. package/src/lib/model/ai-site-look.js +76 -14
  27. package/src/lib/model/ai-site-look.js.map +1 -1
  28. package/src/lib/site-import/fixtures/aglyn-com-recordings.d.ts +2 -1
  29. package/src/lib/site-import/fixtures/aglyn-com-recordings.js +3 -2
  30. package/src/lib/site-import/fixtures/aglyn-com-recordings.js.map +1 -1
  31. package/src/lib/site-import/fixtures/site-import-crawl-recordings.d.ts +5 -0
  32. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js +116 -3
  33. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js.map +1 -1
  34. package/src/lib/site-import/fixtures/site-import-fidelity-replay.d.ts +7 -0
  35. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +15 -0
  36. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
  37. package/src/lib/site-import/fixtures/site-layout-recordings.js +4 -3
  38. package/src/lib/site-import/fixtures/site-layout-recordings.js.map +1 -1
  39. package/src/lib/site-import/fixtures/site-look-slate.d.ts +2 -1
  40. package/src/lib/site-import/fixtures/site-look-slate.js +2 -1
  41. package/src/lib/site-import/fixtures/site-look-slate.js.map +1 -1
  42. package/src/lib/site-import/site-import-crawl.d.ts +7 -1
  43. package/src/lib/site-import/site-import-crawl.js +101 -6
  44. package/src/lib/site-import/site-import-crawl.js.map +1 -1
  45. package/src/lib/site-import/site-import-css.d.ts +8 -1
  46. package/src/lib/site-import/site-import-css.js +30 -8
  47. package/src/lib/site-import/site-import-css.js.map +1 -1
  48. package/src/lib/site-import/site-import-html.d.ts +2 -0
  49. package/src/lib/site-import/site-import-html.js +3 -0
  50. package/src/lib/site-import/site-import-html.js.map +1 -1
  51. package/src/lib/site-import/site-import-layout.d.ts +9 -2
  52. package/src/lib/site-import/site-import-layout.js +104 -30
  53. package/src/lib/site-import/site-import-layout.js.map +1 -1
  54. package/src/lib/site-import/site-import-page.js +5 -0
  55. package/src/lib/site-import/site-import-page.js.map +1 -1
  56. package/src/lib/site-import/site-import-same-page.d.ts +41 -0
  57. package/src/lib/site-import/site-import-same-page.js +108 -0
  58. package/src/lib/site-import/site-import-same-page.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/ai/src/lib/site-import/fixtures/site-look-slate.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/**\n * A home page drawn the way the 11/4 Keep my site evidence was (AGL-4152), in\n * plain markup of no builder's (`site-look/slate-home.html`): a dark slate\n * hero and a second slate band, a near-black closing band, light cyan filled\n * buttons set in capitals under dark words, and a hero heading held to 12 em\n * inside a 1200 px column. What the reader keeps of it, and the theme Keep my\n * site draws from that, is held by `site-import-layout.spec.ts` and\n * `ai-site-import-look.spec.ts`.\n */\n\nexport const SITE_LOOK_SLATE_URL = 'https://www.slate-studio.example/'\n\nexport const SITE_LOOK_SLATE_HTML = readFileSync(join(__dirname, 'site-look', 'slate-home.html'), 'utf8')\n"],"names":["readFileSync","join","SITE_LOOK_SLATE_URL","SITE_LOOK_SLATE_HTML","__dirname"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAQ,UAAS;AACtC,SAASC,IAAI,QAAQ,YAAW;AAEhC;;;;;;;;CAQC,GAED,OAAO,MAAMC,sBAAsB,oCAAmC;AAEtE,OAAO,MAAMC,uBAAuBH,aAAaC,KAAKG,WAAW,aAAa,oBAAoB,QAAO"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/ai/src/lib/site-import/fixtures/site-look-slate.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/**\n * A home page drawn the way the 11/4 Keep my site evidence was (AGL-4152), in\n * plain markup of no builder's (`site-look/slate-home.html`): a dark slate\n * hero and a second slate band, a near-black closing band, light cyan filled\n * buttons set in capitals under dark words, and a hero heading held to 12 em\n * inside a 1200 px column. Its stylesheet says its dark scheme, under a media\n * query and a class on the root (AGL-4152). What the reader keeps of it, and the theme Keep my\n * site draws from that, is held by `site-import-layout.spec.ts` and\n * `ai-site-import-look.spec.ts`.\n */\n\nexport const SITE_LOOK_SLATE_URL = 'https://www.slate-studio.example/'\n\nexport const SITE_LOOK_SLATE_HTML = readFileSync(join(__dirname, 'site-look', 'slate-home.html'), 'utf8')\n"],"names":["readFileSync","join","SITE_LOOK_SLATE_URL","SITE_LOOK_SLATE_HTML","__dirname"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAQ,UAAS;AACtC,SAASC,IAAI,QAAQ,YAAW;AAEhC;;;;;;;;;CASC,GAED,OAAO,MAAMC,sBAAsB,oCAAmC;AAEtE,OAAO,MAAMC,uBAAuBH,aAAaC,KAAKG,WAAW,aAAa,oBAAoB,QAAO"}
@@ -68,7 +68,11 @@ export type SiteImportSkipReason =
68
68
  /** No answer, a private address, or a refused address. */
69
69
  | 'unreachable'
70
70
  /** Never asked for: a stop (time, bytes, the page budget) came first (AGL-4083). */
71
- | 'not-reached';
71
+ | 'not-reached'
72
+ /** Another address of a page already found (AGL-4152). */
73
+ | 'duplicate'
74
+ /** The cart, checkout or account screen the site's platform makes (AGL-4152). */
75
+ | 'system-page';
72
76
  export interface SiteImportSkipped {
73
77
  url: string;
74
78
  reason: SiteImportSkipReason;
@@ -77,6 +81,8 @@ export interface SiteImportSkipped {
77
81
  location?: string;
78
82
  /** Whose edge turned an error answer away, when it said (AGL-4083). */
79
83
  edge?: PublicFetchEdge;
84
+ /** The page a `duplicate` is another address of (AGL-4152). */
85
+ sameAs?: string;
80
86
  }
81
87
  export interface SiteImportPage {
82
88
  /** The address the page was read from, after any same-site redirect. */
@@ -60,6 +60,11 @@ var _process_env_SITE_IMPORT_BOT_INFO_URL;
60
60
  * - **No sign-in pages.** A page with a password field is refused and
61
61
  * reported; forms with payment fields, scripts, iframes and embeds never
62
62
  * reach the inventory (site-import-html.ts).
63
+ * - **Pages, not addresses (AGL-4152).** Another address of a page already
64
+ * found, and a platform's own cart or account screen, are reported and
65
+ * take nothing from the page budget (site-import-same-page.ts). Addresses a
66
+ * link adds a query to wait for the rest. The home page is always a page,
67
+ * and a wave's read is exactly the pages it asks for.
63
68
  *=========================================*/ import { lookalikeBrandForHost } from "@aglyn/shared-util-email/outbound-phishing-screen";
64
69
  import { fenceUntrustedText } from "@aglyn/shared-util-tools/untrusted-text";
65
70
  import { AI_THEME_REFERENCE_STYLESHEETS, AI_THEME_STYLESHEET_MAX_BYTES, fetchPublicTextDetailed } from "../jobs/ai-theme-brand-inputs.js";
@@ -67,6 +72,7 @@ import { extractSiteImportPage, readMetaValues } from "./site-import-html.js";
67
72
  import { AGLYN_BOT_TOKEN, parseRobotsTxt, parseSitemap, robotsAllows, robotsRulesFor } from "./site-import-robots.js";
68
73
  import { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor } from "./site-import-edge.js";
69
74
  import { siteImportLayout, siteImportLookOf } from "./site-import-layout.js";
75
+ import { siteImportAddressOf, siteImportCanonicalBelieved, siteImportCanonicalClaim, siteImportContentSignature, siteImportIsSystemScreen } from "./site-import-same-page.js";
70
76
  import { siteImportFooterColumns, siteImportNavTree } from "./site-import-nav.js";
71
77
  /**
72
78
  * Where the bot's user agent points a site owner who wants to know what it is
@@ -225,7 +231,9 @@ function skipReasonFor(result) {
225
231
  redirectAllowed: (_from, to)=>sameSite(to),
226
232
  refuseOver: true
227
233
  });
234
+ /** Addresses taken in, read or not: one a page is waiting on that is here and is no page will never be. */ const takenIn = new Set();
228
235
  const skip = (entry)=>{
236
+ takenIn.add(siteImportAddressOf(entry.url));
229
237
  if (inventory.skipped.length < SITE_IMPORT_DEFAULTS.maxSkipped) inventory.skipped.push(entry);
230
238
  else inventory.skippedOverflow += 1;
231
239
  };
@@ -324,6 +332,7 @@ function skipReasonFor(result) {
324
332
  foundBy: 'home'
325
333
  }
326
334
  ];
335
+ /** Addresses a link adds a query to, which wait for every other (AGL-4152): a gallery's hundred never starve a page. */ const later = [];
327
336
  const queued = new Set(only != null ? only : [
328
337
  home
329
338
  ]);
@@ -361,6 +370,48 @@ function skipReasonFor(result) {
361
370
  if (remainingBytes() - reserved <= 0) return 'wait';
362
371
  return null;
363
372
  };
373
+ /** The page each address is, its other addresses included. */ const pageAt = new Map();
374
+ /** The first page found with each main content. */ const pageWith = new Map();
375
+ /** Pages whose canonical names an address not yet taken in. */ const waiting = [];
376
+ const place = (page, signature)=>{
377
+ inventory.pages.push(page);
378
+ pageAt.set(siteImportAddressOf(page.url), page);
379
+ if (signature && !pageWith.has(signature)) pageWith.set(signature, page);
380
+ };
381
+ const leaveSameAs = (url, page)=>{
382
+ pageAt.set(siteImportAddressOf(url), page);
383
+ skip({
384
+ url,
385
+ reason: 'duplicate',
386
+ sameAs: page.url
387
+ });
388
+ };
389
+ /** The page this address is another address of; `wait` for the one its canonical names; or `null`, its own page. */ const sameAs = (url, claim, signature)=>{
390
+ const same = signature ? pageWith.get(signature) : undefined;
391
+ if (same) return same;
392
+ if (!claim) return null;
393
+ const named = pageAt.get(siteImportAddressOf(claim));
394
+ if (named) return siteImportCanonicalBelieved(url, claim) ? named : null;
395
+ return takenIn.has(siteImportAddressOf(claim)) ? null : 'wait';
396
+ };
397
+ /** The waiting pages whose answer is in; `last`, all of them: what they named never came, so each stands. */ const settle = (last = false)=>{
398
+ for (const entry of [
399
+ ...waiting
400
+ ]){
401
+ const verdict = sameAs(entry.page.url, entry.claim, entry.signature);
402
+ if (verdict === 'wait' && !last) continue;
403
+ waiting.splice(waiting.indexOf(entry), 1);
404
+ if (verdict && verdict !== 'wait') leaveSameAs(entry.page.url, verdict);
405
+ else if (inventory.pages.length < maxPages) place(entry.page, entry.signature);
406
+ else {
407
+ stop != null ? stop : stop = 'page-budget';
408
+ skip({
409
+ url: entry.page.url,
410
+ reason: 'not-reached'
411
+ });
412
+ }
413
+ }
414
+ };
364
415
  const readLayout = (_options_layout = options.layout) != null ? _options_layout : !!only;
365
416
  /** Linked stylesheets, each asked once a crawl. */ const sheets = new Map();
366
417
  const stylesheet = (url)=>{
@@ -379,6 +430,7 @@ function skipReasonFor(result) {
379
430
  var _siteImportPageKey;
380
431
  const foundBy = next.foundBy;
381
432
  if (foundBy === 'home') homeIn = true;
433
+ takenIn.add(siteImportAddressOf(key));
382
434
  if (!page.ok) {
383
435
  if (page.refusal === 'too-large' && cap < maxPageBytes) {
384
436
  cutOff.push(key);
@@ -405,6 +457,7 @@ function skipReasonFor(result) {
405
457
  inventory.bytesRead += page.bytes;
406
458
  if (foundBy === 'home') preferred = new URL(page.url).origin;
407
459
  const finalKey = canon((_siteImportPageKey = siteImportPageKey(new URL(page.url), origins)) != null ? _siteImportPageKey : page.url);
460
+ takenIn.add(siteImportAddressOf(finalKey));
408
461
  if (finalKey !== key) {
409
462
  if (read.has(finalKey)) return null;
410
463
  read.add(finalKey);
@@ -435,12 +488,30 @@ function skipReasonFor(result) {
435
488
  links.push(linkKey);
436
489
  if (!only && !queued.has(linkKey)) {
437
490
  queued.add(linkKey);
438
- queue.push({
491
+ (new URL(linkKey).search ? later : queue).push({
439
492
  key: linkKey,
440
493
  foundBy: 'link'
441
494
  });
442
495
  }
443
496
  }
497
+ // Whether it is a page of its own (AGL-4152). What is not takes nothing from the budget.
498
+ const own = !only && !isHome;
499
+ if (own && siteImportIsSystemScreen(new URL(finalKey).pathname, extract)) {
500
+ attempts = Math.max(0, attempts - 1);
501
+ skip({
502
+ url: finalKey,
503
+ reason: 'system-page'
504
+ });
505
+ return null;
506
+ }
507
+ const signature = only ? null : siteImportContentSignature(extract);
508
+ const claim = own ? siteImportCanonicalClaim(extract.canonical, finalKey, (url)=>siteImportPageKey(url, origins)) : null;
509
+ const verdict = own ? sameAs(finalKey, claim, signature) : null;
510
+ if (verdict && verdict !== 'wait') {
511
+ attempts = Math.max(0, attempts - 1);
512
+ leaveSameAs(finalKey, verdict);
513
+ return null;
514
+ }
444
515
  // How the page is built (AGL-4106), through its own stylesheets.
445
516
  let built = {};
446
517
  if (extract.structure) {
@@ -469,7 +540,7 @@ function skipReasonFor(result) {
469
540
  });
470
541
  }
471
542
  }
472
- inventory.pages.push(_extends({}, built, {
543
+ const taken = _extends({}, built, {
473
544
  url: finalKey,
474
545
  path: new URL(finalKey).pathname,
475
546
  foundBy,
@@ -493,20 +564,39 @@ function skipReasonFor(result) {
493
564
  videos: extract.videos
494
565
  } : {}, {
495
566
  bytes: page.bytes
496
- }));
567
+ });
568
+ if (verdict === 'wait' && claim) {
569
+ // The page it names comes next, even if nothing else links it.
570
+ attempts = Math.max(0, attempts - 1);
571
+ waiting.push({
572
+ page: taken,
573
+ claim,
574
+ signature
575
+ });
576
+ if (!queued.has(claim) && !read.has(canon(claim))) {
577
+ queued.add(claim);
578
+ queue.unshift({
579
+ key: claim,
580
+ foundBy: 'link'
581
+ });
582
+ }
583
+ return null;
584
+ }
585
+ place(taken, signature);
497
586
  return null;
498
587
  };
499
588
  for(;;){
500
589
  var _ref;
501
590
  const width = homeIn ? SITE_IMPORT_DEFAULTS.concurrency : 1;
502
- while(!stop && queue.length && window.length < width){
591
+ while(!stop && (queue.length || later.length) && window.length < width){
592
+ var _queue_shift;
503
593
  const why = held();
504
594
  if (why === 'wait') break;
505
595
  if (why) {
506
596
  stop = why;
507
597
  break;
508
598
  }
509
- const next = queue.shift();
599
+ const next = (_queue_shift = queue.shift()) != null ? _queue_shift : later.shift();
510
600
  const key = canon(next.key);
511
601
  if (read.has(key)) continue;
512
602
  if (!allowed(key)) {
@@ -532,7 +622,9 @@ function skipReasonFor(result) {
532
622
  const asked = await window.shift();
533
623
  reserved -= asked.cap;
534
624
  stop = (_ref = await takeIn(asked)) != null ? _ref : stop;
625
+ settle();
535
626
  }
627
+ settle(true);
536
628
  inventory.stoppedBy = stop;
537
629
  // Whatever a stop left unread is said, never dropped; a wave's own read
538
630
  // leaves its unread pages for its next pass instead.
@@ -540,7 +632,10 @@ function skipReasonFor(result) {
540
632
  const unread = [
541
633
  ...cutOff
542
634
  ];
543
- for (const next of queue){
635
+ for (const next of [
636
+ ...queue,
637
+ ...later
638
+ ]){
544
639
  const key = canon(next.key);
545
640
  if (!read.has(key) && !unread.includes(key)) unread.push(key);
546
641
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/site-import/site-import-crawl.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE SITE-IMPORT CRAWLER (AGL-3974, parent AGL-3973).\n *\n * Reads a website a workspace has PROVED it owns (domain-ownership.ts in\n * tenant-data-admin; the doors check the proof before calling this) into a\n * typed inventory: each page's title, description, headings and text in\n * order, images and menu links. It writes nothing; the import job decides\n * what becomes a page.\n *\n * Every request goes through `fetchPublicTextDetailed`, the theme job's\n * SSRF-guarded fetch: https on the default port only, public addresses only,\n * the socket pinned to the address checked. On top of that:\n *\n * - **One site.** The site is `https://<domain>` and `https://www.<domain>`,\n * one site to its owner. Every redirect hop and every discovered link must\n * stay on it; a page that redirects anywhere else is refused, not followed.\n * - **AglynBot.** Every request says `AglynBot/1.0 (+<the operator's bot page>)`,\n * and robots.txt is read first and honored for every page: the AglynBot\n * group, else `*`. A robots.txt that answers 404 allows everything; one\n * that cannot be read at all (5xx, no answer) stops the crawl, because\n * \"could not ask\" is not \"allowed\".\n * - **Our own edge.** A site this platform serves gets the edge secret\n * (`site-import-edge.ts`, AGL-4085), which lifts our bot challenge for\n * AglynBot; it is asked per request and per redirect hop, and a request\n * that leaves the site's two origins never carries it.\n * - **Sitemap first.** The sitemaps robots.txt names, else /sitemap.xml (an\n * index's children included), then same-site links found on the pages read,\n * for whatever the sitemap missed.\n * - **Budgets.** Pages (the caller's, from the plan), bytes per page (a page\n * over it is refused, not cut), bytes in total, and wall-clock time. A\n * whole site's worth fits (AGL-4083): aglyn.com's 123 pages average 440 KB,\n * 54 MB in all, so the total is 160 MB; a page is parsed and dropped as it\n * is read, so what is held is its blocks, never its bytes.\n * - **Four at a time.** robots.txt, the sitemaps and the home page are read\n * one after another; the rest four at a time, and the inventory keeps the\n * order they were asked in, which is the sitemap's.\n * - **Nothing vanishes.** An address a stop (the clock, the bytes, the page\n * budget) left unread is listed as `not-reached`, so the inventory's\n * counts add up to the site. A wave's own read leaves its unread pages for\n * its next pass instead.\n * - **No lookalikes.** A domain that wears a brand it is not\n * (`lookalikeBrandForHost`) is refused before any request.\n * - **No sign-in pages.** A page with a password field is refused and\n * reported; forms with payment fields, scripts, iframes and embeds never\n * reach the inventory (site-import-html.ts).\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { fenceUntrustedText } from '@aglyn/shared-util-tools/untrusted-text'\nimport {\n AI_THEME_REFERENCE_STYLESHEETS,\n AI_THEME_STYLESHEET_MAX_BYTES,\n fetchPublicTextDetailed,\n type PublicFetchEdge,\n type PublicFetchOptions,\n type PublicFetchResult,\n} from '../jobs/ai-theme-brand-inputs'\nimport type { SiteImportFooter, SiteImportLayout, SiteImportLookFacts, SiteImportNavTree } from '../model/ai-site-import'\nimport {\n extractSiteImportPage,\n readMetaValues,\n type SiteImportBlock,\n type SiteImportBrandMark,\n type SiteImportForm,\n type SiteImportVideo,\n type SiteImportIcon,\n type SiteImportImage,\n type SiteImportNavLink,\n type SiteImportOrganization,\n} from './site-import-html'\nimport {\n AGLYN_BOT_TOKEN,\n parseRobotsTxt,\n parseSitemap,\n robotsAllows,\n robotsRulesFor,\n type RobotsRule,\n} from './site-import-robots'\nimport { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor, type SiteImportHeadersFor } from './site-import-edge'\nimport { siteImportLayout, siteImportLookOf } from './site-import-layout'\nimport { siteImportFooterColumns, siteImportNavTree } from './site-import-nav'\n\n/**\n * Where the bot's user agent points a site owner who wants to know what it is\n * (AGL-3983): the operator's own page about it. `SITE_IMPORT_BOT_INFO_URL` on\n * a self-hosted deployment, so its crawler never names Aglyn's address; the\n * literal is only that variable's default.\n *\n * Aglyn's is the Bring my site guide, which says what AglynBot reads and how\n * robots.txt keeps it out. There is no page of its own (Zach, 10/20: \"we don't\n * need a bot page at all\"), and the site it reads is the reader's own: an\n * import starts only once its owner has proved the site is theirs.\n */\nexport const AGLYN_BOT_INFO_URL =\n process.env['SITE_IMPORT_BOT_INFO_URL'] ?? 'https://docs.aglyn.com/ai/bring-my-site'\n\n/** What every crawler request says it is. */\nexport const AGLYN_BOT_USER_AGENT = `AglynBot/1.0 (+${AGLYN_BOT_INFO_URL})`\n\nexport const SITE_IMPORT_DEFAULTS = {\n maxPageBytes: 2 * 1024 * 1024,\n /**\n * A whole site's worth (AGL-4083): 54 MB for aglyn.com's 123 pages, with\n * room; 400 pages at its 440 KB average are 176 MB (AGL-4106).\n */\n maxTotalBytes: 320 * 1024 * 1024,\n timeBudgetMs: 60_000,\n /** One request's own clock, inside the whole crawl's. */\n requestTimeoutMs: 8_000,\n robotsMaxBytes: 256 * 1024,\n sitemapMaxBytes: 4 * 1024 * 1024,\n /** Sitemap documents read, an index's children included: an index of six children is seven. */\n maxSitemaps: 24,\n /** URLs a sitemap may contribute to the queue. */\n maxSitemapUrls: 2_000,\n /** Reasons kept in `skipped` before the list stops growing: every address a sitemap may name. */\n maxSkipped: 2_000,\n /** Pages read at once, after robots.txt, the sitemaps and the home page. */\n concurrency: 4,\n} as const\n\n/** Never a page: files a link may point at that are not HTML. */\nconst NON_PAGE_EXTENSION =\n /\\.(?:pdf|jpe?g|png|gif|webp|avif|svg|ico|bmp|tiff?|zip|gz|tgz|rar|7z|mp4|m4v|mov|webm|mp3|wav|ogg|m4a|docx?|xlsx?|pptx?|csv|txt|css|js|mjs|json|xml|rss|atom|woff2?|ttf|otf|eot|exe|dmg|apk)$/i\n\nconst TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|mc_cid|mc_eid|_ga|ref)$/i\n\n/**\n * Never a page, whatever its extension (AGL-4106): an API's or a CDN's path\n * (aglyn.com's press kit links 136 `/api/media/cdn/…?download=1` files) and\n * any address that asks for a download.\n */\nconst NON_PAGE_PATH = /^\\/(?:api|cdn-cgi|wp-json|_next\\/static|_next\\/image)(?:\\/|$)/i\nconst DOWNLOAD_PARAM = /^(?:download|dl|attachment)$/i\n\nconst DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/\n\nexport type SiteImportSkipReason =\n /** The page has a password field: a sign-in page, refused outright. */\n | 'login-form'\n /** robots.txt keeps AglynBot off this path. */\n | 'robots'\n /** A redirect left the site. */\n | 'off-origin-redirect'\n /** Over the per-page byte cap. */\n | 'too-large'\n /** Answered with something that is not HTML. */\n | 'not-html'\n /** Answered 4xx or 5xx. */\n | 'http-error'\n /** No answer, a private address, or a refused address. */\n | 'unreachable'\n /** Never asked for: a stop (time, bytes, the page budget) came first (AGL-4083). */\n | 'not-reached'\n\nexport interface SiteImportSkipped {\n url: string\n reason: SiteImportSkipReason\n status?: number\n /** Where an off-origin redirect pointed. */\n location?: string\n /** Whose edge turned an error answer away, when it said (AGL-4083). */\n edge?: PublicFetchEdge\n}\n\nexport interface SiteImportPage {\n /** The address the page was read from, after any same-site redirect. */\n url: string\n path: string\n /** Where the crawler learned of the page. */\n foundBy: 'home' | 'sitemap' | 'link'\n title: string\n description: string\n lang: string | null\n canonical: string | null\n /** The share card (AGL-4083). */\n ogImage: string | null\n /** The site's own name, as its head gives it. */\n siteName: string\n icons: SiteImportIcon[]\n /** The header's link home: the brand's logo and words. */\n brand: SiteImportBrandMark | null\n organization: SiteImportOrganization | null\n blocks: SiteImportBlock[]\n images: SiteImportImage[]\n navLinks: SiteImportNavLink[]\n /** Same-site page addresses this page links to. */\n links: string[]\n forms: { kept: SiteImportForm[]; removed: number }\n /** Its videos (AGL-4140), each once; absent on a page with none. */\n videos?: SiteImportVideo[]\n bytes: number\n /** How the source lays the page out (AGL-4106), on a read asked for it (`layout`): a wave's. */\n layout?: SiteImportLayout | null\n /** The home page's menu, footer and look, as its source builds them (AGL-4106). */\n nav?: SiteImportNavTree | null\n footer?: SiteImportFooter | null\n look?: SiteImportLookFacts | null\n}\n\nexport type SiteImportStop =\n | 'page-budget'\n | 'total-bytes'\n | 'time'\n /** robots.txt could not be read, so nothing was asked of the site. */\n | 'robots-unreachable'\n\nexport interface SiteImportInventory {\n domain: string\n /** The site's origins: the bare name and its `www.` twin. */\n origins: string[]\n /** Set when nothing was fetched at all. */\n refused: 'invalid-domain' | 'lookalike' | null\n pages: SiteImportPage[]\n skipped: SiteImportSkipped[]\n /** Skips past {@link SITE_IMPORT_DEFAULTS.maxSkipped}, counted only. */\n skippedOverflow: number\n robots: { found: boolean; sitemaps: string[] }\n /** Page addresses the sitemaps listed (same-site, before robots and budget). */\n sitemapUrls: number\n stoppedBy: SiteImportStop | null\n bytesRead: number\n startedAt: number\n finishedAt: number\n}\n\nexport interface SiteImportCrawlOptions {\n /** The proved domain; `www.` is folded in. */\n domain: string\n /** The most pages the inventory may hold: the plan's page count. */\n maxPages: number\n maxPageBytes?: number\n maxTotalBytes?: number\n timeBudgetMs?: number\n signal?: AbortSignal\n /**\n * Read the sitemap's shallow addresses before its deep ones (AGL-3976), so a\n * crawl the page budget stops reads a site's main pages before the tail of\n * its blog. A sitemap's own order is kept among addresses of one depth.\n */\n shallowFirst?: boolean\n /**\n * Read exactly these addresses of the site, in order, and nothing else\n * (AGL-3976): an import's wave reads its own pages again when it starts. No\n * sitemap is read and no link is followed; robots.txt is read and honored\n * as for any crawl, and every other rule holds.\n */\n only?: readonly string[]\n /**\n * Read how each page is laid out (AGL-4106): its structure, through its own\n * stylesheets (the first two it links, each asked once a crawl). On by\n * default for a wave's read (`only`), whose pages are built; the home page's\n * menu, footer and look are read on every crawl.\n */\n layout?: boolean\n}\n\nexport interface SiteImportCrawlSeams {\n fetch?: (url: string, options: PublicFetchOptions) => Promise<PublicFetchResult>\n now?: () => number\n /**\n * Request headers for the site being read, asked once per crawl with its\n * domain (AGL-4083, AGL-4085). Absent, the crawl asks the edge\n * (`siteImportEdgeHeadersFor`): Aglyn's edge secret for each of the site's\n * two origins this platform serves, decided origin by origin, and nothing\n * anywhere else. Either way the headers go only to the site's two origins,\n * and the fetch asks again on every redirect hop, so a hop anywhere else\n * carries nothing. Always under the crawler's own `Accept` and `User-Agent`.\n */\n headersFor?: (domain: string) => Promise<Readonly<Record<string, string>>> | Readonly<Record<string, string>>\n}\n\n/**\n * The per-request headers of a crawl of `domain`: the seam's, else the edge's,\n * and none for any address off the site's two origins. Never throws.\n */\nasync function siteRequestHeaders(\n seams: SiteImportCrawlSeams,\n domain: string,\n origins: readonly string[],\n): Promise<SiteImportHeadersFor> {\n let inner: SiteImportHeadersFor = NO_SITE_IMPORT_HEADERS\n try {\n if (seams.headersFor) {\n const headers = await seams.headersFor(domain)\n if (headers && Object.keys(headers).length) inner = () => headers\n } else {\n inner = await siteImportEdgeHeadersFor(origins)\n }\n } catch (error) {\n console.warn('[site-import] the edge headers could not be read; reading without them', { domain, error })\n }\n return (url: URL) => (origins.includes(url.origin) ? inner(url) : {})\n}\n\n/** The site's two origins for a domain. */\nexport function siteImportOrigins(domain: string): string[] {\n const bare = domain.replace(/^www\\./, '')\n return [`https://${bare}`, `https://www.${bare}`]\n}\n\n/** A crawlable page address on the site, normalized for de-duplication; else null. */\nexport function siteImportPageKey(url: URL, origins: readonly string[]): string | null {\n if (url.protocol !== 'https:' || url.username || url.password) return null\n if (url.port && url.port !== '443') return null\n if (!origins.includes(url.origin)) return null\n if (NON_PAGE_EXTENSION.test(url.pathname) || NON_PAGE_PATH.test(url.pathname)) return null\n if ([...url.searchParams.keys()].some((key) => DOWNLOAD_PARAM.test(key))) return null\n const clean = new URL(url.toString())\n clean.hash = ''\n for (const key of [...clean.searchParams.keys()]) {\n if (TRACKING_PARAM.test(key)) clean.searchParams.delete(key)\n }\n clean.search = clean.searchParams.toString() ? `?${clean.searchParams.toString()}` : ''\n return clean.toString()\n}\n\nfunction skipReasonFor(result: PublicFetchResult): SiteImportSkipReason {\n switch (result.refusal) {\n case 'redirect-refused':\n return 'off-origin-redirect'\n case 'content-type':\n return 'not-html'\n case 'too-large':\n return 'too-large'\n case 'http-status':\n return 'http-error'\n default:\n return 'unreachable'\n }\n}\n\n/** Read a proved site into an inventory. Never throws for anything the site does. */\nexport async function crawlSiteForImport(\n options: SiteImportCrawlOptions,\n seams: SiteImportCrawlSeams = {},\n): Promise<SiteImportInventory> {\n const now = seams.now ?? Date.now\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const domain = String(options.domain ?? '').trim().toLowerCase().replace(/\\.+$/, '').replace(/^www\\./, '')\n const origins = DOMAIN_PATTERN.test(domain) ? siteImportOrigins(domain) : []\n const startedAt = now()\n const inventory: SiteImportInventory = {\n domain,\n origins,\n refused: null,\n pages: [],\n skipped: [],\n skippedOverflow: 0,\n robots: { found: false, sitemaps: [] },\n sitemapUrls: 0,\n stoppedBy: null,\n bytesRead: 0,\n startedAt,\n finishedAt: startedAt,\n }\n const finish = () => {\n inventory.finishedAt = now()\n return inventory\n }\n if (!origins.length) {\n inventory.refused = 'invalid-domain'\n return finish()\n }\n if (lookalikeBrandForHost(domain)) {\n inventory.refused = 'lookalike'\n return finish()\n }\n\n // Asked once, before anything else, and held to the site's two origins.\n const headersFor = await siteRequestHeaders(seams, domain, origins)\n const maxPages = Math.max(0, Math.floor(options.maxPages))\n const maxPageBytes = options.maxPageBytes ?? SITE_IMPORT_DEFAULTS.maxPageBytes\n const maxTotalBytes = options.maxTotalBytes ?? SITE_IMPORT_DEFAULTS.maxTotalBytes\n const deadlineAt = startedAt + (options.timeBudgetMs ?? SITE_IMPORT_DEFAULTS.timeBudgetMs)\n const controller = new AbortController()\n const onAbort = () => controller.abort()\n options.signal?.addEventListener('abort', onAbort)\n if (options.signal?.aborted) controller.abort()\n const timer = setTimeout(() => controller.abort(), Math.max(0, deadlineAt - startedAt))\n\n const sameSite = (url: URL) => origins.includes(url.origin) && url.protocol === 'https:'\n const remainingBytes = () => maxTotalBytes - inventory.bytesRead\n const outOfTime = () => controller.signal.aborted || now() >= deadlineAt\n const request = (url: string, accept: RegExp, acceptHeader: string, maxBytes: number) =>\n fetchText(url, {\n maxBytes,\n accept,\n acceptHeader,\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor,\n signal: controller.signal,\n timeoutMs: Math.max(1, Math.min(SITE_IMPORT_DEFAULTS.requestTimeoutMs, deadlineAt - now())),\n redirectAllowed: (_from, to) => sameSite(to),\n refuseOver: true,\n })\n const skip = (entry: SiteImportSkipped) => {\n if (inventory.skipped.length < SITE_IMPORT_DEFAULTS.maxSkipped) inventory.skipped.push(entry)\n else inventory.skippedOverflow += 1\n }\n\n try {\n // robots.txt, before anything else is asked of the site.\n const home = `${origins[0]}/`\n let rules: RobotsRule[] = []\n const robots = await request(\n `${origins[0]}/robots.txt`,\n /text\\/plain|text\\/html|^$/i,\n 'text/plain',\n Math.min(SITE_IMPORT_DEFAULTS.robotsMaxBytes, remainingBytes()),\n )\n if (robots.ok) {\n inventory.bytesRead += robots.bytes\n const parsed = parseRobotsTxt(robots.text)\n rules = robotsRulesFor(parsed, AGLYN_BOT_TOKEN)\n inventory.robots = { found: true, sitemaps: parsed.sitemaps }\n } else if (\n !(robots.refusal === 'http-status' && (robots.status ?? 0) >= 400 && (robots.status ?? 0) < 500)\n ) {\n inventory.stoppedBy = outOfTime() ? 'time' : 'robots-unreachable'\n return finish()\n }\n const allowed = (key: string) => {\n const url = new URL(key)\n return robotsAllows(rules, `${url.pathname}${url.search}`)\n }\n\n // A wave's own pages (AGL-3976): exactly those, after robots.txt.\n const only = options.only\n ? options.only\n .map((raw) => {\n try {\n return siteImportPageKey(new URL(raw), origins)\n } catch {\n return null\n }\n })\n .filter((key): key is string => !!key)\n : null\n\n // Sitemaps: the ones robots.txt names on this site, else /sitemap.xml.\n const sitemapQueue: string[] = []\n for (const raw of inventory.robots.sitemaps) {\n try {\n const url = new URL(raw)\n if (sameSite(url)) sitemapQueue.push(url.toString())\n } catch {\n // A malformed Sitemap line names nothing.\n }\n }\n if (!sitemapQueue.length && !only) sitemapQueue.push(`${origins[0]}/sitemap.xml`)\n if (only) sitemapQueue.length = 0\n const sitemapSeen = new Set<string>()\n const fromSitemap: string[] = []\n let sitemapsRead = 0\n while (sitemapQueue.length && sitemapsRead < SITE_IMPORT_DEFAULTS.maxSitemaps && !outOfTime()) {\n const next = sitemapQueue.shift() as string\n if (sitemapSeen.has(next)) continue\n sitemapSeen.add(next)\n if (/\\.gz$/i.test(new URL(next).pathname)) continue\n if (!allowed(next)) continue\n const room = Math.min(SITE_IMPORT_DEFAULTS.sitemapMaxBytes, remainingBytes())\n if (room <= 0) break\n sitemapsRead += 1\n const sitemap = await request(next, /xml|text\\/plain/i, 'application/xml, text/xml;q=0.9', room)\n if (!sitemap.ok) continue\n inventory.bytesRead += sitemap.bytes\n const entries = parseSitemap(sitemap.text)\n for (const location of entries.locations) {\n let url: URL\n try {\n url = new URL(location)\n } catch {\n continue\n }\n if (entries.index) {\n if (sameSite(url)) sitemapQueue.push(url.toString())\n continue\n }\n const key = siteImportPageKey(url, origins)\n if (key && fromSitemap.length < SITE_IMPORT_DEFAULTS.maxSitemapUrls) fromSitemap.push(key)\n }\n }\n inventory.sitemapUrls = fromSitemap.length\n if (options.shallowFirst) {\n const depth = (key: string) => new URL(key).pathname.split('/').filter(Boolean).length\n const ranked = fromSitemap.map((key, order) => ({ key, order, depth: depth(key) }))\n ranked.sort((a, b) => a.depth - b.depth || a.order - b.order)\n fromSitemap.splice(0, fromSitemap.length, ...ranked.map((entry) => entry.key))\n }\n\n // Pages: home, then the sitemap's, then links the pages themselves name.\n // A wave's read is its own pages alone.\n const queue: { key: string; foundBy: SiteImportPage['foundBy'] }[] = only\n ? only.map((key) => ({ key, foundBy: (new URL(key).pathname === '/' ? 'home' : 'link') as SiteImportPage['foundBy'] }))\n : [{ key: home, foundBy: 'home' }]\n const queued = new Set<string>(only ?? [home])\n for (const key of fromSitemap) {\n if (queued.has(key)) continue\n queued.add(key)\n queue.push({ key, foundBy: 'sitemap' })\n }\n const read = new Set<string>()\n // The site's two names are one site: once the home page says which one\n // it answers on, every address is read on that one, so /about is not\n // read twice as example.com/about and www.example.com/about.\n // A wave's read starts on the name its pages were read on the first time.\n let preferred = only?.length ? new URL(only[0]).origin : origins[0]\n const canon = (raw: string) => {\n const url = new URL(raw)\n return origins.includes(url.origin) && url.origin !== preferred\n ? `${preferred}${url.pathname}${url.search}`\n : raw\n }\n const maxAttempts = maxPages * 3 + 10\n let attempts = 0\n type Asked = { next: (typeof queue)[number]; key: string; cap: number; page: PublicFetchResult }\n /** The pages asked for and not yet taken in, in the order they were asked. */\n const window: Array<Promise<Asked>> = []\n /** The bytes the asked pages may still read: what is left is shared, never promised twice. */\n let reserved = 0\n let stop: SiteImportStop | null = null\n /** Asked for and never read, because a stop came first: listed as not reached. */\n const cutOff: string[] = []\n /** Home alone first, so its answer settles which of the site's two names the rest are read on. */\n let homeIn = !!only\n /** Why no more may be asked now: a stop, `wait` for an asked page to come in first, or nothing. */\n const held = (): SiteImportStop | 'wait' | null => {\n if (inventory.pages.length >= maxPages) return 'page-budget'\n if (outOfTime()) return 'time'\n if (remainingBytes() <= 0) return 'total-bytes'\n if (attempts >= maxAttempts) return 'page-budget'\n if (inventory.pages.length + window.length >= maxPages) return 'wait'\n if (remainingBytes() - reserved <= 0) return 'wait'\n return null\n }\n const readLayout = options.layout ?? !!only\n /** Linked stylesheets, each asked once a crawl. */\n const sheets = new Map<string, Promise<string | null>>()\n const stylesheet = (url: string): Promise<string | null> => {\n const held = sheets.get(url)\n if (held) return held\n const room = Math.min(AI_THEME_STYLESHEET_MAX_BYTES, remainingBytes() - reserved)\n const asked: Promise<string | null> =\n room <= 0 || outOfTime()\n ? Promise.resolve(null)\n : request(url, /text\\/css|text\\/plain/i, 'text/css,*/*;q=0.1', room).then(\n (answer) => {\n if (!answer.ok) return null\n inventory.bytesRead += answer.bytes\n return answer.text\n },\n () => null,\n )\n sheets.set(url, asked)\n return asked\n }\n /** Takes one asked page in: the inventory's next page, a skip, or the reason the read must stop. */\n const takeIn = async ({ next, key, cap, page }: Asked): Promise<SiteImportStop | null> => {\n const foundBy = next.foundBy\n if (foundBy === 'home') homeIn = true\n if (!page.ok) {\n if (page.refusal === 'too-large' && cap < maxPageBytes) {\n cutOff.push(key)\n return 'total-bytes'\n }\n if (page.refusal === 'network' && outOfTime()) {\n cutOff.push(key)\n return 'time'\n }\n // A file is not a page: it takes nothing from the page budget's attempts (AGL-4106).\n if (page.refusal === 'content-type') attempts = Math.max(0, attempts - 1)\n skip({\n url: key,\n reason: skipReasonFor(page),\n ...(page.status ? { status: page.status } : {}),\n ...(page.location ? { location: page.location } : {}),\n ...(page.edge ? { edge: page.edge } : {}),\n })\n return null\n }\n inventory.bytesRead += page.bytes\n if (foundBy === 'home') preferred = new URL(page.url).origin\n const finalKey = canon(siteImportPageKey(new URL(page.url), origins) ?? page.url)\n if (finalKey !== key) {\n if (read.has(finalKey)) return null\n read.add(finalKey)\n if (!allowed(finalKey)) {\n skip({ url: finalKey, reason: 'robots' })\n return null\n }\n }\n const isHome = foundBy === 'home'\n const structured = readLayout || isHome\n const extract = extractSiteImportPage(page.text, page.url, sameSite, { structure: structured })\n if (extract.loginForm) {\n skip({ url: finalKey, reason: 'login-form' })\n return null\n }\n const links: string[] = []\n for (const link of extract.links) {\n const linkKey = siteImportPageKey(new URL(link), origins)\n if (!linkKey) continue\n links.push(linkKey)\n if (!only && !queued.has(linkKey)) {\n queued.add(linkKey)\n queue.push({ key: linkKey, foundBy: 'link' })\n }\n }\n // How the page is built (AGL-4106), through its own stylesheets.\n let built: Pick<SiteImportPage, 'layout' | 'nav' | 'footer' | 'look'> = {}\n if (extract.structure) {\n const linked = await Promise.all(extract.structure.stylesheets.filter((url) => !/fonts\\.googleapis\\.com/i.test(url)).slice(0, AI_THEME_REFERENCE_STYLESHEETS).map(stylesheet))\n const css = linked.filter((text): text is string => typeof text === 'string')\n const source = { blocks: extract.blocks, organization: extract.organization, structure: extract.structure, ...(extract.videos ? { videos: extract.videos } : {}) }\n try {\n built = {\n ...(readLayout ? { layout: siteImportLayout(source, css) } : {}),\n ...(isHome ? { nav: siteImportNavTree(source, css), footer: siteImportFooterColumns(source, css), look: siteImportLookOf(source, css) } : {}),\n }\n } catch (error) {\n // A page the reader cannot lay out is still its words.\n console.warn('[site-import] the layout could not be read', { url: page.url, error })\n }\n }\n inventory.pages.push({\n ...built,\n url: finalKey,\n path: new URL(finalKey).pathname,\n foundBy,\n title: extract.title,\n description: extract.description,\n lang: extract.lang,\n canonical: extract.canonical,\n ogImage: extract.ogImage,\n siteName: extract.siteName,\n icons: extract.icons,\n brand: extract.brand,\n organization: extract.organization,\n blocks: extract.blocks,\n images: extract.images,\n navLinks: extract.navLinks,\n links: [...new Set(links.map(canon))],\n forms: extract.forms,\n ...(extract.videos ? { videos: extract.videos } : {}),\n bytes: page.bytes,\n })\n return null\n }\n for (;;) {\n const width = homeIn ? SITE_IMPORT_DEFAULTS.concurrency : 1\n while (!stop && queue.length && window.length < width) {\n const why = held()\n if (why === 'wait') break\n if (why) {\n stop = why\n break\n }\n const next = queue.shift() as (typeof queue)[number]\n const key = canon(next.key)\n if (read.has(key)) continue\n if (!allowed(key)) {\n skip({ url: key, reason: 'robots' })\n if (next.foundBy === 'home') homeIn = true\n continue\n }\n attempts += 1\n read.add(key)\n const cap = Math.min(maxPageBytes, remainingBytes() - reserved)\n reserved += cap\n window.push(\n request(key, /text\\/html|application\\/xhtml\\+xml/i, 'text/html, application/xhtml+xml;q=0.9', cap).then((page) => ({ next, key, cap, page })),\n )\n }\n if (!window.length) break\n const asked = await (window.shift() as Promise<Asked>)\n reserved -= asked.cap\n stop = (await takeIn(asked)) ?? stop\n }\n inventory.stoppedBy = stop\n // Whatever a stop left unread is said, never dropped; a wave's own read\n // leaves its unread pages for its next pass instead.\n if (stop && !only) {\n const unread = [...cutOff]\n for (const next of queue) {\n const key = canon(next.key)\n if (!read.has(key) && !unread.includes(key)) unread.push(key)\n }\n for (const url of unread) skip({ url, reason: 'not-reached' })\n }\n return finish()\n } finally {\n clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n }\n}\n\n/**\n * The home page's `aglyn-site-verification` values, for the meta-tag proof:\n * the same fetch, user agent and same-site redirects as the crawl, but no\n * robots.txt, because the person asked for this one page to be read.\n * `answered: false` when the page could not be read at all.\n */\nexport async function readSiteVerificationMeta(\n domain: string,\n metaName: string,\n seams: SiteImportCrawlSeams = {},\n): Promise<{ answered: boolean; values: string[]; url?: string }> {\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const bare = String(domain ?? '').trim().toLowerCase().replace(/^www\\./, '')\n if (!DOMAIN_PATTERN.test(bare) || lookalikeBrandForHost(bare)) return { answered: false, values: [] }\n const origins = siteImportOrigins(bare)\n const result = await fetchText(`${origins[0]}/`, {\n maxBytes: SITE_IMPORT_DEFAULTS.maxPageBytes,\n accept: /text\\/html|application\\/xhtml\\+xml/i,\n acceptHeader: 'text/html, application/xhtml+xml;q=0.9',\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor: await siteRequestHeaders(seams, bare, origins),\n timeoutMs: SITE_IMPORT_DEFAULTS.requestTimeoutMs,\n redirectAllowed: (_from, to) => to.protocol === 'https:' && origins.includes(to.origin),\n })\n if (!result.ok) {\n // An answer that is not the page (a 404, a redirect off the site) is\n // still an answer: the tag is not where it must be.\n const answered = result.refusal === 'http-status' || result.refusal === 'redirect-refused' || result.refusal === 'content-type'\n return { answered, values: [], url: result.url }\n }\n const head = result.text.split(/<body\\b/i)[0] ?? ''\n return { answered: true, values: readMetaValues(head, metaName), url: result.url }\n}\n\n/**\n * One page as text for a prompt: its title, description and blocks in order,\n * fenced as untrusted data. The importer's prompt carries `UNTRUSTED_TEXT_RULE`.\n */\nexport function siteImportPagePromptText(page: SiteImportPage, maxChars = 12_000): string {\n const lines: string[] = []\n if (page.title) lines.push(`Title: ${page.title}`)\n if (page.description) lines.push(`Description: ${page.description}`)\n for (const block of page.blocks) {\n if (block.kind === 'heading') lines.push(`${'#'.repeat(block.level)} ${block.text}`)\n else if (block.kind === 'image') lines.push(`[image: ${block.alt || 'no description'}]`)\n else if (block.kind === 'list-item') lines.push(`- ${block.text}`)\n else if (block.kind === 'quote') lines.push(`> ${block.text}`)\n else if (block.kind === 'link') {\n // A link inside a sentence is in its block's words already.\n if (!block.inline) lines.push(block.text)\n } else lines.push(block.text)\n }\n return fenceUntrustedText(`Page ${page.path} of the site being imported`, lines.join('\\n'), { maxChars })\n}\n"],"names":["process","lookalikeBrandForHost","fenceUntrustedText","AI_THEME_REFERENCE_STYLESHEETS","AI_THEME_STYLESHEET_MAX_BYTES","fetchPublicTextDetailed","extractSiteImportPage","readMetaValues","AGLYN_BOT_TOKEN","parseRobotsTxt","parseSitemap","robotsAllows","robotsRulesFor","NO_SITE_IMPORT_HEADERS","siteImportEdgeHeadersFor","siteImportLayout","siteImportLookOf","siteImportFooterColumns","siteImportNavTree","AGLYN_BOT_INFO_URL","env","AGLYN_BOT_USER_AGENT","SITE_IMPORT_DEFAULTS","maxPageBytes","maxTotalBytes","timeBudgetMs","requestTimeoutMs","robotsMaxBytes","sitemapMaxBytes","maxSitemaps","maxSitemapUrls","maxSkipped","concurrency","NON_PAGE_EXTENSION","TRACKING_PARAM","NON_PAGE_PATH","DOWNLOAD_PARAM","DOMAIN_PATTERN","siteRequestHeaders","seams","domain","origins","inner","headersFor","headers","Object","keys","length","error","console","warn","url","includes","origin","siteImportOrigins","bare","replace","siteImportPageKey","protocol","username","password","port","test","pathname","searchParams","some","key","clean","URL","toString","hash","delete","search","skipReasonFor","result","refusal","crawlSiteForImport","options","now","Date","fetchText","fetch","String","trim","toLowerCase","startedAt","inventory","refused","pages","skipped","skippedOverflow","robots","found","sitemaps","sitemapUrls","stoppedBy","bytesRead","finishedAt","finish","maxPages","Math","max","floor","deadlineAt","controller","AbortController","onAbort","abort","signal","addEventListener","aborted","timer","setTimeout","sameSite","remainingBytes","outOfTime","request","accept","acceptHeader","maxBytes","userAgent","timeoutMs","min","redirectAllowed","_from","to","refuseOver","skip","entry","push","home","rules","ok","bytes","parsed","text","status","allowed","only","map","raw","filter","sitemapQueue","sitemapSeen","Set","fromSitemap","sitemapsRead","next","shift","has","add","room","sitemap","entries","location","locations","index","shallowFirst","depth","split","Boolean","ranked","order","sort","a","b","splice","queue","foundBy","queued","read","preferred","canon","maxAttempts","attempts","window","reserved","stop","cutOff","homeIn","held","readLayout","layout","sheets","Map","stylesheet","get","asked","Promise","resolve","then","answer","set","takeIn","cap","page","reason","edge","finalKey","isHome","structured","extract","structure","loginForm","links","link","linkKey","built","linked","all","stylesheets","slice","css","source","blocks","organization","videos","nav","footer","look","path","title","description","lang","canonical","ogImage","siteName","icons","brand","images","navLinks","forms","width","why","unread","clearTimeout","removeEventListener","readSiteVerificationMeta","metaName","answered","values","head","siteImportPagePromptText","maxChars","lines","block","kind","repeat","level","alt","inline","join"],"mappings":";IA+GEA;AA/GF;;;;;;;;;;;;;;;CAeC,GAED;;;;;;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AC/B,IAAI+B,MAAMC,IAAI,KAAK,WAAWF,MAAMnH,IAAI,CAAC,GAAG,IAAIsH,MAAM,CAACF,MAAMG,KAAK,EAAE,CAAC,EAAEH,MAAM9G,IAAI,EAAE;aAC9E,IAAI8G,MAAMC,IAAI,KAAK,SAASF,MAAMnH,IAAI,CAAC,CAAC,QAAQ,EAAEoH,MAAMI,GAAG,IAAI,iBAAiB,CAAC,CAAC;aAClF,IAAIJ,MAAMC,IAAI,KAAK,aAAaF,MAAMnH,IAAI,CAAC,CAAC,EAAE,EAAEoH,MAAM9G,IAAI,EAAE;aAC5D,IAAI8G,MAAMC,IAAI,KAAK,SAASF,MAAMnH,IAAI,CAAC,CAAC,EAAE,EAAEoH,MAAM9G,IAAI,EAAE;aACxD,IAAI8G,MAAMC,IAAI,KAAK,QAAQ;YAC9B,4DAA4D;YAC5D,IAAI,CAACD,MAAMK,MAAM,EAAEN,MAAMnH,IAAI,CAACoH,MAAM9G,IAAI;QAC1C,OAAO6G,MAAMnH,IAAI,CAACoH,MAAM9G,IAAI;IAC9B;IACA,OAAOrI,mBAAmB,CAAC,KAAK,EAAEiM,KAAKyB,IAAI,CAAC,2BAA2B,CAAC,EAAEwB,MAAMO,IAAI,CAAC,OAAO;QAAER;IAAS;AACzG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/site-import/site-import-crawl.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE SITE-IMPORT CRAWLER (AGL-3974, parent AGL-3973).\n *\n * Reads a website a workspace has PROVED it owns (domain-ownership.ts in\n * tenant-data-admin; the doors check the proof before calling this) into a\n * typed inventory: each page's title, description, headings and text in\n * order, images and menu links. It writes nothing; the import job decides\n * what becomes a page.\n *\n * Every request goes through `fetchPublicTextDetailed`, the theme job's\n * SSRF-guarded fetch: https on the default port only, public addresses only,\n * the socket pinned to the address checked. On top of that:\n *\n * - **One site.** The site is `https://<domain>` and `https://www.<domain>`,\n * one site to its owner. Every redirect hop and every discovered link must\n * stay on it; a page that redirects anywhere else is refused, not followed.\n * - **AglynBot.** Every request says `AglynBot/1.0 (+<the operator's bot page>)`,\n * and robots.txt is read first and honored for every page: the AglynBot\n * group, else `*`. A robots.txt that answers 404 allows everything; one\n * that cannot be read at all (5xx, no answer) stops the crawl, because\n * \"could not ask\" is not \"allowed\".\n * - **Our own edge.** A site this platform serves gets the edge secret\n * (`site-import-edge.ts`, AGL-4085), which lifts our bot challenge for\n * AglynBot; it is asked per request and per redirect hop, and a request\n * that leaves the site's two origins never carries it.\n * - **Sitemap first.** The sitemaps robots.txt names, else /sitemap.xml (an\n * index's children included), then same-site links found on the pages read,\n * for whatever the sitemap missed.\n * - **Budgets.** Pages (the caller's, from the plan), bytes per page (a page\n * over it is refused, not cut), bytes in total, and wall-clock time. A\n * whole site's worth fits (AGL-4083): aglyn.com's 123 pages average 440 KB,\n * 54 MB in all, so the total is 160 MB; a page is parsed and dropped as it\n * is read, so what is held is its blocks, never its bytes.\n * - **Four at a time.** robots.txt, the sitemaps and the home page are read\n * one after another; the rest four at a time, and the inventory keeps the\n * order they were asked in, which is the sitemap's.\n * - **Nothing vanishes.** An address a stop (the clock, the bytes, the page\n * budget) left unread is listed as `not-reached`, so the inventory's\n * counts add up to the site. A wave's own read leaves its unread pages for\n * its next pass instead.\n * - **No lookalikes.** A domain that wears a brand it is not\n * (`lookalikeBrandForHost`) is refused before any request.\n * - **No sign-in pages.** A page with a password field is refused and\n * reported; forms with payment fields, scripts, iframes and embeds never\n * reach the inventory (site-import-html.ts).\n * - **Pages, not addresses (AGL-4152).** Another address of a page already\n * found, and a platform's own cart or account screen, are reported and\n * take nothing from the page budget (site-import-same-page.ts). Addresses a\n * link adds a query to wait for the rest. The home page is always a page,\n * and a wave's read is exactly the pages it asks for.\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { fenceUntrustedText } from '@aglyn/shared-util-tools/untrusted-text'\nimport {\n AI_THEME_REFERENCE_STYLESHEETS,\n AI_THEME_STYLESHEET_MAX_BYTES,\n fetchPublicTextDetailed,\n type PublicFetchEdge,\n type PublicFetchOptions,\n type PublicFetchResult,\n} from '../jobs/ai-theme-brand-inputs'\nimport type { SiteImportFooter, SiteImportLayout, SiteImportLookFacts, SiteImportNavTree } from '../model/ai-site-import'\nimport {\n extractSiteImportPage,\n readMetaValues,\n type SiteImportBlock,\n type SiteImportBrandMark,\n type SiteImportForm,\n type SiteImportVideo,\n type SiteImportIcon,\n type SiteImportImage,\n type SiteImportNavLink,\n type SiteImportOrganization,\n} from './site-import-html'\nimport {\n AGLYN_BOT_TOKEN,\n parseRobotsTxt,\n parseSitemap,\n robotsAllows,\n robotsRulesFor,\n type RobotsRule,\n} from './site-import-robots'\nimport { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor, type SiteImportHeadersFor } from './site-import-edge'\nimport { siteImportLayout, siteImportLookOf } from './site-import-layout'\nimport {\n siteImportAddressOf,\n siteImportCanonicalBelieved,\n siteImportCanonicalClaim,\n siteImportContentSignature,\n siteImportIsSystemScreen,\n} from './site-import-same-page'\nimport { siteImportFooterColumns, siteImportNavTree } from './site-import-nav'\n\n/**\n * Where the bot's user agent points a site owner who wants to know what it is\n * (AGL-3983): the operator's own page about it. `SITE_IMPORT_BOT_INFO_URL` on\n * a self-hosted deployment, so its crawler never names Aglyn's address; the\n * literal is only that variable's default.\n *\n * Aglyn's is the Bring my site guide, which says what AglynBot reads and how\n * robots.txt keeps it out. There is no page of its own (Zach, 10/20: \"we don't\n * need a bot page at all\"), and the site it reads is the reader's own: an\n * import starts only once its owner has proved the site is theirs.\n */\nexport const AGLYN_BOT_INFO_URL =\n process.env['SITE_IMPORT_BOT_INFO_URL'] ?? 'https://docs.aglyn.com/ai/bring-my-site'\n\n/** What every crawler request says it is. */\nexport const AGLYN_BOT_USER_AGENT = `AglynBot/1.0 (+${AGLYN_BOT_INFO_URL})`\n\nexport const SITE_IMPORT_DEFAULTS = {\n maxPageBytes: 2 * 1024 * 1024,\n /**\n * A whole site's worth (AGL-4083): 54 MB for aglyn.com's 123 pages, with\n * room; 400 pages at its 440 KB average are 176 MB (AGL-4106).\n */\n maxTotalBytes: 320 * 1024 * 1024,\n timeBudgetMs: 60_000,\n /** One request's own clock, inside the whole crawl's. */\n requestTimeoutMs: 8_000,\n robotsMaxBytes: 256 * 1024,\n sitemapMaxBytes: 4 * 1024 * 1024,\n /** Sitemap documents read, an index's children included: an index of six children is seven. */\n maxSitemaps: 24,\n /** URLs a sitemap may contribute to the queue. */\n maxSitemapUrls: 2_000,\n /** Reasons kept in `skipped` before the list stops growing: every address a sitemap may name. */\n maxSkipped: 2_000,\n /** Pages read at once, after robots.txt, the sitemaps and the home page. */\n concurrency: 4,\n} as const\n\n/** Never a page: files a link may point at that are not HTML. */\nconst NON_PAGE_EXTENSION =\n /\\.(?:pdf|jpe?g|png|gif|webp|avif|svg|ico|bmp|tiff?|zip|gz|tgz|rar|7z|mp4|m4v|mov|webm|mp3|wav|ogg|m4a|docx?|xlsx?|pptx?|csv|txt|css|js|mjs|json|xml|rss|atom|woff2?|ttf|otf|eot|exe|dmg|apk)$/i\n\nconst TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|mc_cid|mc_eid|_ga|ref)$/i\n\n/**\n * Never a page, whatever its extension (AGL-4106): an API's or a CDN's path\n * (aglyn.com's press kit links 136 `/api/media/cdn/…?download=1` files) and\n * any address that asks for a download.\n */\nconst NON_PAGE_PATH = /^\\/(?:api|cdn-cgi|wp-json|_next\\/static|_next\\/image)(?:\\/|$)/i\nconst DOWNLOAD_PARAM = /^(?:download|dl|attachment)$/i\n\nconst DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/\n\nexport type SiteImportSkipReason =\n /** The page has a password field: a sign-in page, refused outright. */\n | 'login-form'\n /** robots.txt keeps AglynBot off this path. */\n | 'robots'\n /** A redirect left the site. */\n | 'off-origin-redirect'\n /** Over the per-page byte cap. */\n | 'too-large'\n /** Answered with something that is not HTML. */\n | 'not-html'\n /** Answered 4xx or 5xx. */\n | 'http-error'\n /** No answer, a private address, or a refused address. */\n | 'unreachable'\n /** Never asked for: a stop (time, bytes, the page budget) came first (AGL-4083). */\n | 'not-reached'\n /** Another address of a page already found (AGL-4152). */\n | 'duplicate'\n /** The cart, checkout or account screen the site's platform makes (AGL-4152). */\n | 'system-page'\n\nexport interface SiteImportSkipped {\n url: string\n reason: SiteImportSkipReason\n status?: number\n /** Where an off-origin redirect pointed. */\n location?: string\n /** Whose edge turned an error answer away, when it said (AGL-4083). */\n edge?: PublicFetchEdge\n /** The page a `duplicate` is another address of (AGL-4152). */\n sameAs?: string\n}\n\nexport interface SiteImportPage {\n /** The address the page was read from, after any same-site redirect. */\n url: string\n path: string\n /** Where the crawler learned of the page. */\n foundBy: 'home' | 'sitemap' | 'link'\n title: string\n description: string\n lang: string | null\n canonical: string | null\n /** The share card (AGL-4083). */\n ogImage: string | null\n /** The site's own name, as its head gives it. */\n siteName: string\n icons: SiteImportIcon[]\n /** The header's link home: the brand's logo and words. */\n brand: SiteImportBrandMark | null\n organization: SiteImportOrganization | null\n blocks: SiteImportBlock[]\n images: SiteImportImage[]\n navLinks: SiteImportNavLink[]\n /** Same-site page addresses this page links to. */\n links: string[]\n forms: { kept: SiteImportForm[]; removed: number }\n /** Its videos (AGL-4140), each once; absent on a page with none. */\n videos?: SiteImportVideo[]\n bytes: number\n /** How the source lays the page out (AGL-4106), on a read asked for it (`layout`): a wave's. */\n layout?: SiteImportLayout | null\n /** The home page's menu, footer and look, as its source builds them (AGL-4106). */\n nav?: SiteImportNavTree | null\n footer?: SiteImportFooter | null\n look?: SiteImportLookFacts | null\n}\n\nexport type SiteImportStop =\n | 'page-budget'\n | 'total-bytes'\n | 'time'\n /** robots.txt could not be read, so nothing was asked of the site. */\n | 'robots-unreachable'\n\nexport interface SiteImportInventory {\n domain: string\n /** The site's origins: the bare name and its `www.` twin. */\n origins: string[]\n /** Set when nothing was fetched at all. */\n refused: 'invalid-domain' | 'lookalike' | null\n pages: SiteImportPage[]\n skipped: SiteImportSkipped[]\n /** Skips past {@link SITE_IMPORT_DEFAULTS.maxSkipped}, counted only. */\n skippedOverflow: number\n robots: { found: boolean; sitemaps: string[] }\n /** Page addresses the sitemaps listed (same-site, before robots and budget). */\n sitemapUrls: number\n stoppedBy: SiteImportStop | null\n bytesRead: number\n startedAt: number\n finishedAt: number\n}\n\nexport interface SiteImportCrawlOptions {\n /** The proved domain; `www.` is folded in. */\n domain: string\n /** The most pages the inventory may hold: the plan's page count. */\n maxPages: number\n maxPageBytes?: number\n maxTotalBytes?: number\n timeBudgetMs?: number\n signal?: AbortSignal\n /**\n * Read the sitemap's shallow addresses before its deep ones (AGL-3976), so a\n * crawl the page budget stops reads a site's main pages before the tail of\n * its blog. A sitemap's own order is kept among addresses of one depth.\n */\n shallowFirst?: boolean\n /**\n * Read exactly these addresses of the site, in order, and nothing else\n * (AGL-3976): an import's wave reads its own pages again when it starts. No\n * sitemap is read and no link is followed; robots.txt is read and honored\n * as for any crawl, and every other rule holds.\n */\n only?: readonly string[]\n /**\n * Read how each page is laid out (AGL-4106): its structure, through its own\n * stylesheets (the first two it links, each asked once a crawl). On by\n * default for a wave's read (`only`), whose pages are built; the home page's\n * menu, footer and look are read on every crawl.\n */\n layout?: boolean\n}\n\nexport interface SiteImportCrawlSeams {\n fetch?: (url: string, options: PublicFetchOptions) => Promise<PublicFetchResult>\n now?: () => number\n /**\n * Request headers for the site being read, asked once per crawl with its\n * domain (AGL-4083, AGL-4085). Absent, the crawl asks the edge\n * (`siteImportEdgeHeadersFor`): Aglyn's edge secret for each of the site's\n * two origins this platform serves, decided origin by origin, and nothing\n * anywhere else. Either way the headers go only to the site's two origins,\n * and the fetch asks again on every redirect hop, so a hop anywhere else\n * carries nothing. Always under the crawler's own `Accept` and `User-Agent`.\n */\n headersFor?: (domain: string) => Promise<Readonly<Record<string, string>>> | Readonly<Record<string, string>>\n}\n\n/**\n * The per-request headers of a crawl of `domain`: the seam's, else the edge's,\n * and none for any address off the site's two origins. Never throws.\n */\nasync function siteRequestHeaders(\n seams: SiteImportCrawlSeams,\n domain: string,\n origins: readonly string[],\n): Promise<SiteImportHeadersFor> {\n let inner: SiteImportHeadersFor = NO_SITE_IMPORT_HEADERS\n try {\n if (seams.headersFor) {\n const headers = await seams.headersFor(domain)\n if (headers && Object.keys(headers).length) inner = () => headers\n } else {\n inner = await siteImportEdgeHeadersFor(origins)\n }\n } catch (error) {\n console.warn('[site-import] the edge headers could not be read; reading without them', { domain, error })\n }\n return (url: URL) => (origins.includes(url.origin) ? inner(url) : {})\n}\n\n/** The site's two origins for a domain. */\nexport function siteImportOrigins(domain: string): string[] {\n const bare = domain.replace(/^www\\./, '')\n return [`https://${bare}`, `https://www.${bare}`]\n}\n\n/** A crawlable page address on the site, normalized for de-duplication; else null. */\nexport function siteImportPageKey(url: URL, origins: readonly string[]): string | null {\n if (url.protocol !== 'https:' || url.username || url.password) return null\n if (url.port && url.port !== '443') return null\n if (!origins.includes(url.origin)) return null\n if (NON_PAGE_EXTENSION.test(url.pathname) || NON_PAGE_PATH.test(url.pathname)) return null\n if ([...url.searchParams.keys()].some((key) => DOWNLOAD_PARAM.test(key))) return null\n const clean = new URL(url.toString())\n clean.hash = ''\n for (const key of [...clean.searchParams.keys()]) {\n if (TRACKING_PARAM.test(key)) clean.searchParams.delete(key)\n }\n clean.search = clean.searchParams.toString() ? `?${clean.searchParams.toString()}` : ''\n return clean.toString()\n}\n\nfunction skipReasonFor(result: PublicFetchResult): SiteImportSkipReason {\n switch (result.refusal) {\n case 'redirect-refused':\n return 'off-origin-redirect'\n case 'content-type':\n return 'not-html'\n case 'too-large':\n return 'too-large'\n case 'http-status':\n return 'http-error'\n default:\n return 'unreachable'\n }\n}\n\n/** Read a proved site into an inventory. Never throws for anything the site does. */\nexport async function crawlSiteForImport(\n options: SiteImportCrawlOptions,\n seams: SiteImportCrawlSeams = {},\n): Promise<SiteImportInventory> {\n const now = seams.now ?? Date.now\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const domain = String(options.domain ?? '').trim().toLowerCase().replace(/\\.+$/, '').replace(/^www\\./, '')\n const origins = DOMAIN_PATTERN.test(domain) ? siteImportOrigins(domain) : []\n const startedAt = now()\n const inventory: SiteImportInventory = {\n domain,\n origins,\n refused: null,\n pages: [],\n skipped: [],\n skippedOverflow: 0,\n robots: { found: false, sitemaps: [] },\n sitemapUrls: 0,\n stoppedBy: null,\n bytesRead: 0,\n startedAt,\n finishedAt: startedAt,\n }\n const finish = () => {\n inventory.finishedAt = now()\n return inventory\n }\n if (!origins.length) {\n inventory.refused = 'invalid-domain'\n return finish()\n }\n if (lookalikeBrandForHost(domain)) {\n inventory.refused = 'lookalike'\n return finish()\n }\n\n // Asked once, before anything else, and held to the site's two origins.\n const headersFor = await siteRequestHeaders(seams, domain, origins)\n const maxPages = Math.max(0, Math.floor(options.maxPages))\n const maxPageBytes = options.maxPageBytes ?? SITE_IMPORT_DEFAULTS.maxPageBytes\n const maxTotalBytes = options.maxTotalBytes ?? SITE_IMPORT_DEFAULTS.maxTotalBytes\n const deadlineAt = startedAt + (options.timeBudgetMs ?? SITE_IMPORT_DEFAULTS.timeBudgetMs)\n const controller = new AbortController()\n const onAbort = () => controller.abort()\n options.signal?.addEventListener('abort', onAbort)\n if (options.signal?.aborted) controller.abort()\n const timer = setTimeout(() => controller.abort(), Math.max(0, deadlineAt - startedAt))\n\n const sameSite = (url: URL) => origins.includes(url.origin) && url.protocol === 'https:'\n const remainingBytes = () => maxTotalBytes - inventory.bytesRead\n const outOfTime = () => controller.signal.aborted || now() >= deadlineAt\n const request = (url: string, accept: RegExp, acceptHeader: string, maxBytes: number) =>\n fetchText(url, {\n maxBytes,\n accept,\n acceptHeader,\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor,\n signal: controller.signal,\n timeoutMs: Math.max(1, Math.min(SITE_IMPORT_DEFAULTS.requestTimeoutMs, deadlineAt - now())),\n redirectAllowed: (_from, to) => sameSite(to),\n refuseOver: true,\n })\n /** Addresses taken in, read or not: one a page is waiting on that is here and is no page will never be. */\n const takenIn = new Set<string>()\n const skip = (entry: SiteImportSkipped) => {\n takenIn.add(siteImportAddressOf(entry.url))\n if (inventory.skipped.length < SITE_IMPORT_DEFAULTS.maxSkipped) inventory.skipped.push(entry)\n else inventory.skippedOverflow += 1\n }\n\n try {\n // robots.txt, before anything else is asked of the site.\n const home = `${origins[0]}/`\n let rules: RobotsRule[] = []\n const robots = await request(\n `${origins[0]}/robots.txt`,\n /text\\/plain|text\\/html|^$/i,\n 'text/plain',\n Math.min(SITE_IMPORT_DEFAULTS.robotsMaxBytes, remainingBytes()),\n )\n if (robots.ok) {\n inventory.bytesRead += robots.bytes\n const parsed = parseRobotsTxt(robots.text)\n rules = robotsRulesFor(parsed, AGLYN_BOT_TOKEN)\n inventory.robots = { found: true, sitemaps: parsed.sitemaps }\n } else if (\n !(robots.refusal === 'http-status' && (robots.status ?? 0) >= 400 && (robots.status ?? 0) < 500)\n ) {\n inventory.stoppedBy = outOfTime() ? 'time' : 'robots-unreachable'\n return finish()\n }\n const allowed = (key: string) => {\n const url = new URL(key)\n return robotsAllows(rules, `${url.pathname}${url.search}`)\n }\n\n // A wave's own pages (AGL-3976): exactly those, after robots.txt.\n const only = options.only\n ? options.only\n .map((raw) => {\n try {\n return siteImportPageKey(new URL(raw), origins)\n } catch {\n return null\n }\n })\n .filter((key): key is string => !!key)\n : null\n\n // Sitemaps: the ones robots.txt names on this site, else /sitemap.xml.\n const sitemapQueue: string[] = []\n for (const raw of inventory.robots.sitemaps) {\n try {\n const url = new URL(raw)\n if (sameSite(url)) sitemapQueue.push(url.toString())\n } catch {\n // A malformed Sitemap line names nothing.\n }\n }\n if (!sitemapQueue.length && !only) sitemapQueue.push(`${origins[0]}/sitemap.xml`)\n if (only) sitemapQueue.length = 0\n const sitemapSeen = new Set<string>()\n const fromSitemap: string[] = []\n let sitemapsRead = 0\n while (sitemapQueue.length && sitemapsRead < SITE_IMPORT_DEFAULTS.maxSitemaps && !outOfTime()) {\n const next = sitemapQueue.shift() as string\n if (sitemapSeen.has(next)) continue\n sitemapSeen.add(next)\n if (/\\.gz$/i.test(new URL(next).pathname)) continue\n if (!allowed(next)) continue\n const room = Math.min(SITE_IMPORT_DEFAULTS.sitemapMaxBytes, remainingBytes())\n if (room <= 0) break\n sitemapsRead += 1\n const sitemap = await request(next, /xml|text\\/plain/i, 'application/xml, text/xml;q=0.9', room)\n if (!sitemap.ok) continue\n inventory.bytesRead += sitemap.bytes\n const entries = parseSitemap(sitemap.text)\n for (const location of entries.locations) {\n let url: URL\n try {\n url = new URL(location)\n } catch {\n continue\n }\n if (entries.index) {\n if (sameSite(url)) sitemapQueue.push(url.toString())\n continue\n }\n const key = siteImportPageKey(url, origins)\n if (key && fromSitemap.length < SITE_IMPORT_DEFAULTS.maxSitemapUrls) fromSitemap.push(key)\n }\n }\n inventory.sitemapUrls = fromSitemap.length\n if (options.shallowFirst) {\n const depth = (key: string) => new URL(key).pathname.split('/').filter(Boolean).length\n const ranked = fromSitemap.map((key, order) => ({ key, order, depth: depth(key) }))\n ranked.sort((a, b) => a.depth - b.depth || a.order - b.order)\n fromSitemap.splice(0, fromSitemap.length, ...ranked.map((entry) => entry.key))\n }\n\n // Pages: home, then the sitemap's, then links the pages themselves name.\n // A wave's read is its own pages alone.\n const queue: { key: string; foundBy: SiteImportPage['foundBy'] }[] = only\n ? only.map((key) => ({ key, foundBy: (new URL(key).pathname === '/' ? 'home' : 'link') as SiteImportPage['foundBy'] }))\n : [{ key: home, foundBy: 'home' }]\n /** Addresses a link adds a query to, which wait for every other (AGL-4152): a gallery's hundred never starve a page. */\n const later: typeof queue = []\n const queued = new Set<string>(only ?? [home])\n for (const key of fromSitemap) {\n if (queued.has(key)) continue\n queued.add(key)\n queue.push({ key, foundBy: 'sitemap' })\n }\n const read = new Set<string>()\n // The site's two names are one site: once the home page says which one\n // it answers on, every address is read on that one, so /about is not\n // read twice as example.com/about and www.example.com/about.\n // A wave's read starts on the name its pages were read on the first time.\n let preferred = only?.length ? new URL(only[0]).origin : origins[0]\n const canon = (raw: string) => {\n const url = new URL(raw)\n return origins.includes(url.origin) && url.origin !== preferred\n ? `${preferred}${url.pathname}${url.search}`\n : raw\n }\n const maxAttempts = maxPages * 3 + 10\n let attempts = 0\n type Asked = { next: (typeof queue)[number]; key: string; cap: number; page: PublicFetchResult }\n /** The pages asked for and not yet taken in, in the order they were asked. */\n const window: Array<Promise<Asked>> = []\n /** The bytes the asked pages may still read: what is left is shared, never promised twice. */\n let reserved = 0\n let stop: SiteImportStop | null = null\n /** Asked for and never read, because a stop came first: listed as not reached. */\n const cutOff: string[] = []\n /** Home alone first, so its answer settles which of the site's two names the rest are read on. */\n let homeIn = !!only\n /** Why no more may be asked now: a stop, `wait` for an asked page to come in first, or nothing. */\n const held = (): SiteImportStop | 'wait' | null => {\n if (inventory.pages.length >= maxPages) return 'page-budget'\n if (outOfTime()) return 'time'\n if (remainingBytes() <= 0) return 'total-bytes'\n if (attempts >= maxAttempts) return 'page-budget'\n if (inventory.pages.length + window.length >= maxPages) return 'wait'\n if (remainingBytes() - reserved <= 0) return 'wait'\n return null\n }\n /** The page each address is, its other addresses included. */\n const pageAt = new Map<string, SiteImportPage>()\n /** The first page found with each main content. */\n const pageWith = new Map<string, SiteImportPage>()\n /** Pages whose canonical names an address not yet taken in. */\n const waiting: Array<{ page: SiteImportPage; claim: string; signature: string | null }> = []\n const place = (page: SiteImportPage, signature: string | null) => {\n inventory.pages.push(page)\n pageAt.set(siteImportAddressOf(page.url), page)\n if (signature && !pageWith.has(signature)) pageWith.set(signature, page)\n }\n const leaveSameAs = (url: string, page: SiteImportPage) => {\n pageAt.set(siteImportAddressOf(url), page)\n skip({ url, reason: 'duplicate', sameAs: page.url })\n }\n /** The page this address is another address of; `wait` for the one its canonical names; or `null`, its own page. */\n const sameAs = (url: string, claim: string | null, signature: string | null): SiteImportPage | 'wait' | null => {\n const same = signature ? pageWith.get(signature) : undefined\n if (same) return same\n if (!claim) return null\n const named = pageAt.get(siteImportAddressOf(claim))\n if (named) return siteImportCanonicalBelieved(url, claim) ? named : null\n return takenIn.has(siteImportAddressOf(claim)) ? null : 'wait'\n }\n /** The waiting pages whose answer is in; `last`, all of them: what they named never came, so each stands. */\n const settle = (last = false) => {\n for (const entry of [...waiting]) {\n const verdict = sameAs(entry.page.url, entry.claim, entry.signature)\n if (verdict === 'wait' && !last) continue\n waiting.splice(waiting.indexOf(entry), 1)\n if (verdict && verdict !== 'wait') leaveSameAs(entry.page.url, verdict)\n else if (inventory.pages.length < maxPages) place(entry.page, entry.signature)\n else {\n stop ??= 'page-budget'\n skip({ url: entry.page.url, reason: 'not-reached' })\n }\n }\n }\n const readLayout = options.layout ?? !!only\n /** Linked stylesheets, each asked once a crawl. */\n const sheets = new Map<string, Promise<string | null>>()\n const stylesheet = (url: string): Promise<string | null> => {\n const held = sheets.get(url)\n if (held) return held\n const room = Math.min(AI_THEME_STYLESHEET_MAX_BYTES, remainingBytes() - reserved)\n const asked: Promise<string | null> =\n room <= 0 || outOfTime()\n ? Promise.resolve(null)\n : request(url, /text\\/css|text\\/plain/i, 'text/css,*/*;q=0.1', room).then(\n (answer) => {\n if (!answer.ok) return null\n inventory.bytesRead += answer.bytes\n return answer.text\n },\n () => null,\n )\n sheets.set(url, asked)\n return asked\n }\n /** Takes one asked page in: the inventory's next page, a skip, or the reason the read must stop. */\n const takeIn = async ({ next, key, cap, page }: Asked): Promise<SiteImportStop | null> => {\n const foundBy = next.foundBy\n if (foundBy === 'home') homeIn = true\n takenIn.add(siteImportAddressOf(key))\n if (!page.ok) {\n if (page.refusal === 'too-large' && cap < maxPageBytes) {\n cutOff.push(key)\n return 'total-bytes'\n }\n if (page.refusal === 'network' && outOfTime()) {\n cutOff.push(key)\n return 'time'\n }\n // A file is not a page: it takes nothing from the page budget's attempts (AGL-4106).\n if (page.refusal === 'content-type') attempts = Math.max(0, attempts - 1)\n skip({\n url: key,\n reason: skipReasonFor(page),\n ...(page.status ? { status: page.status } : {}),\n ...(page.location ? { location: page.location } : {}),\n ...(page.edge ? { edge: page.edge } : {}),\n })\n return null\n }\n inventory.bytesRead += page.bytes\n if (foundBy === 'home') preferred = new URL(page.url).origin\n const finalKey = canon(siteImportPageKey(new URL(page.url), origins) ?? page.url)\n takenIn.add(siteImportAddressOf(finalKey))\n if (finalKey !== key) {\n if (read.has(finalKey)) return null\n read.add(finalKey)\n if (!allowed(finalKey)) {\n skip({ url: finalKey, reason: 'robots' })\n return null\n }\n }\n const isHome = foundBy === 'home'\n const structured = readLayout || isHome\n const extract = extractSiteImportPage(page.text, page.url, sameSite, { structure: structured })\n if (extract.loginForm) {\n skip({ url: finalKey, reason: 'login-form' })\n return null\n }\n const links: string[] = []\n for (const link of extract.links) {\n const linkKey = siteImportPageKey(new URL(link), origins)\n if (!linkKey) continue\n links.push(linkKey)\n if (!only && !queued.has(linkKey)) {\n queued.add(linkKey)\n ;(new URL(linkKey).search ? later : queue).push({ key: linkKey, foundBy: 'link' })\n }\n }\n // Whether it is a page of its own (AGL-4152). What is not takes nothing from the budget.\n const own = !only && !isHome\n if (own && siteImportIsSystemScreen(new URL(finalKey).pathname, extract)) {\n attempts = Math.max(0, attempts - 1)\n skip({ url: finalKey, reason: 'system-page' })\n return null\n }\n const signature = only ? null : siteImportContentSignature(extract)\n const claim = own ? siteImportCanonicalClaim(extract.canonical, finalKey, (url) => siteImportPageKey(url, origins)) : null\n const verdict = own ? sameAs(finalKey, claim, signature) : null\n if (verdict && verdict !== 'wait') {\n attempts = Math.max(0, attempts - 1)\n leaveSameAs(finalKey, verdict)\n return null\n }\n // How the page is built (AGL-4106), through its own stylesheets.\n let built: Pick<SiteImportPage, 'layout' | 'nav' | 'footer' | 'look'> = {}\n if (extract.structure) {\n const linked = await Promise.all(extract.structure.stylesheets.filter((url) => !/fonts\\.googleapis\\.com/i.test(url)).slice(0, AI_THEME_REFERENCE_STYLESHEETS).map(stylesheet))\n const css = linked.filter((text): text is string => typeof text === 'string')\n const source = { blocks: extract.blocks, organization: extract.organization, structure: extract.structure, ...(extract.videos ? { videos: extract.videos } : {}) }\n try {\n built = {\n ...(readLayout ? { layout: siteImportLayout(source, css) } : {}),\n ...(isHome ? { nav: siteImportNavTree(source, css), footer: siteImportFooterColumns(source, css), look: siteImportLookOf(source, css) } : {}),\n }\n } catch (error) {\n // A page the reader cannot lay out is still its words.\n console.warn('[site-import] the layout could not be read', { url: page.url, error })\n }\n }\n const taken: SiteImportPage = {\n ...built,\n url: finalKey,\n path: new URL(finalKey).pathname,\n foundBy,\n title: extract.title,\n description: extract.description,\n lang: extract.lang,\n canonical: extract.canonical,\n ogImage: extract.ogImage,\n siteName: extract.siteName,\n icons: extract.icons,\n brand: extract.brand,\n organization: extract.organization,\n blocks: extract.blocks,\n images: extract.images,\n navLinks: extract.navLinks,\n links: [...new Set(links.map(canon))],\n forms: extract.forms,\n ...(extract.videos ? { videos: extract.videos } : {}),\n bytes: page.bytes,\n }\n if (verdict === 'wait' && claim) {\n // The page it names comes next, even if nothing else links it.\n attempts = Math.max(0, attempts - 1)\n waiting.push({ page: taken, claim, signature })\n if (!queued.has(claim) && !read.has(canon(claim))) {\n queued.add(claim)\n queue.unshift({ key: claim, foundBy: 'link' })\n }\n return null\n }\n place(taken, signature)\n return null\n }\n for (;;) {\n const width = homeIn ? SITE_IMPORT_DEFAULTS.concurrency : 1\n while (!stop && (queue.length || later.length) && window.length < width) {\n const why = held()\n if (why === 'wait') break\n if (why) {\n stop = why\n break\n }\n const next = (queue.shift() ?? later.shift()) as (typeof queue)[number]\n const key = canon(next.key)\n if (read.has(key)) continue\n if (!allowed(key)) {\n skip({ url: key, reason: 'robots' })\n if (next.foundBy === 'home') homeIn = true\n continue\n }\n attempts += 1\n read.add(key)\n const cap = Math.min(maxPageBytes, remainingBytes() - reserved)\n reserved += cap\n window.push(\n request(key, /text\\/html|application\\/xhtml\\+xml/i, 'text/html, application/xhtml+xml;q=0.9', cap).then((page) => ({ next, key, cap, page })),\n )\n }\n if (!window.length) break\n const asked = await (window.shift() as Promise<Asked>)\n reserved -= asked.cap\n stop = (await takeIn(asked)) ?? stop\n settle()\n }\n settle(true)\n inventory.stoppedBy = stop\n // Whatever a stop left unread is said, never dropped; a wave's own read\n // leaves its unread pages for its next pass instead.\n if (stop && !only) {\n const unread = [...cutOff]\n for (const next of [...queue, ...later]) {\n const key = canon(next.key)\n if (!read.has(key) && !unread.includes(key)) unread.push(key)\n }\n for (const url of unread) skip({ url, reason: 'not-reached' })\n }\n return finish()\n } finally {\n clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n }\n}\n\n/**\n * The home page's `aglyn-site-verification` values, for the meta-tag proof:\n * the same fetch, user agent and same-site redirects as the crawl, but no\n * robots.txt, because the person asked for this one page to be read.\n * `answered: false` when the page could not be read at all.\n */\nexport async function readSiteVerificationMeta(\n domain: string,\n metaName: string,\n seams: SiteImportCrawlSeams = {},\n): Promise<{ answered: boolean; values: string[]; url?: string }> {\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const bare = String(domain ?? '').trim().toLowerCase().replace(/^www\\./, '')\n if (!DOMAIN_PATTERN.test(bare) || lookalikeBrandForHost(bare)) return { answered: false, values: [] }\n const origins = siteImportOrigins(bare)\n const result = await fetchText(`${origins[0]}/`, {\n maxBytes: SITE_IMPORT_DEFAULTS.maxPageBytes,\n accept: /text\\/html|application\\/xhtml\\+xml/i,\n acceptHeader: 'text/html, application/xhtml+xml;q=0.9',\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor: await siteRequestHeaders(seams, bare, origins),\n timeoutMs: SITE_IMPORT_DEFAULTS.requestTimeoutMs,\n redirectAllowed: (_from, to) => to.protocol === 'https:' && origins.includes(to.origin),\n })\n if (!result.ok) {\n // An answer that is not the page (a 404, a redirect off the site) is\n // still an answer: the tag is not where it must be.\n const answered = result.refusal === 'http-status' || result.refusal === 'redirect-refused' || result.refusal === 'content-type'\n return { answered, values: [], url: result.url }\n }\n const head = result.text.split(/<body\\b/i)[0] ?? ''\n return { answered: true, values: readMetaValues(head, metaName), url: result.url }\n}\n\n/**\n * One page as text for a prompt: its title, description and blocks in order,\n * fenced as untrusted data. The importer's prompt carries `UNTRUSTED_TEXT_RULE`.\n */\nexport function siteImportPagePromptText(page: SiteImportPage, maxChars = 12_000): string {\n const lines: string[] = []\n if (page.title) lines.push(`Title: ${page.title}`)\n if (page.description) lines.push(`Description: ${page.description}`)\n for (const block of page.blocks) {\n if (block.kind === 'heading') lines.push(`${'#'.repeat(block.level)} ${block.text}`)\n else if (block.kind === 'image') lines.push(`[image: ${block.alt || 'no description'}]`)\n else if (block.kind === 'list-item') lines.push(`- ${block.text}`)\n else if (block.kind === 'quote') lines.push(`> ${block.text}`)\n else if (block.kind === 'link') {\n // A link inside a sentence is in its block's words already.\n if (!block.inline) lines.push(block.text)\n } else lines.push(block.text)\n }\n return fenceUntrustedText(`Page ${page.path} of the site being imported`, lines.join('\\n'), { maxChars })\n}\n"],"names":["process","lookalikeBrandForHost","fenceUntrustedText","AI_THEME_REFERENCE_STYLESHEETS","AI_THEME_STYLESHEET_MAX_BYTES","fetchPublicTextDetailed","extractSiteImportPage","readMetaValues","AGLYN_BOT_TOKEN","parseRobotsTxt","parseSitemap","robotsAllows","robotsRulesFor","NO_SITE_IMPORT_HEADERS","siteImportEdgeHeadersFor","siteImportLayout","siteImportLookOf","siteImportAddressOf","siteImportCanonicalBelieved","siteImportCanonicalClaim","siteImportContentSignature","siteImportIsSystemScreen","siteImportFooterColumns","siteImportNavTree","AGLYN_BOT_INFO_URL","env","AGLYN_BOT_USER_AGENT","SITE_IMPORT_DEFAULTS","maxPageBytes","maxTotalBytes","timeBudgetMs","requestTimeoutMs","robotsMaxBytes","sitemapMaxBytes","maxSitemaps","maxSitemapUrls","maxSkipped","concurrency","NON_PAGE_EXTENSION","TRACKING_PARAM","NON_PAGE_PATH","DOWNLOAD_PARAM","DOMAIN_PATTERN","siteRequestHeaders","seams","domain","origins","inner","headersFor","headers","Object","keys","length","error","console","warn","url","includes","origin","siteImportOrigins","bare","replace","siteImportPageKey","protocol","username","password","port","test","pathname","searchParams","some","key","clean","URL","toString","hash","delete","search","skipReasonFor","result","refusal","crawlSiteForImport","options","now","Date","fetchText","fetch","String","trim","toLowerCase","startedAt","inventory","refused","pages","skipped","skippedOverflow","robots","found","sitemaps","sitemapUrls","stoppedBy","bytesRead","finishedAt","finish","maxPages","Math","max","floor","deadlineAt","controller","AbortController","onAbort","abort","signal","addEventListener","aborted","timer","setTimeout","sameSite","remainingBytes","outOfTime","request","accept","acceptHeader","maxBytes","userAgent","timeoutMs","min","redirectAllowed","_from","to","refuseOver","takenIn","Set","skip","entry","add","push","home","rules","ok","bytes","parsed","text","status","allowed","only","map","raw","filter","sitemapQueue","sitemapSeen","fromSitemap","sitemapsRead","next","shift","has","room","sitemap","entries","location","locations","index","shallowFirst","depth","split","Boolean","ranked","order","sort","a","b","splice","queue","foundBy","later","queued","read","preferred","canon","maxAttempts","attempts","window","reserved","stop","cutOff","homeIn","held","pageAt","Map","pageWith","waiting","place","page","signature","set","leaveSameAs","reason","sameAs","claim","same","get","undefined","named","settle","last","verdict","indexOf","readLayout","layout","sheets","stylesheet","asked","Promise","resolve","then","answer","takeIn","cap","edge","finalKey","isHome","structured","extract","structure","loginForm","links","link","linkKey","own","canonical","built","linked","all","stylesheets","slice","css","source","blocks","organization","videos","nav","footer","look","taken","path","title","description","lang","ogImage","siteName","icons","brand","images","navLinks","forms","unshift","width","why","unread","clearTimeout","removeEventListener","readSiteVerificationMeta","metaName","answered","values","head","siteImportPagePromptText","maxChars","lines","block","kind","repeat","level","alt","inline","join"],"mappings":";IA2HEA;AA3HF;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAkD2C,GAE3C,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,kBAAkB,QAAQ,0CAAyC;AAC5E,SACEC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,uBAAuB,QAIlB,mCAA+B;AAEtC,SACEC,qBAAqB,EACrBC,cAAc,QAST,wBAAoB;AAC3B,SACEC,eAAe,EACfC,cAAc,EACdC,YAAY,EACZC,YAAY,EACZC,cAAc,QAET,0BAAsB;AAC7B,SAASC,sBAAsB,EAAEC,wBAAwB,QAAmC,wBAAoB;AAChH,SAASC,gBAAgB,EAAEC,gBAAgB,QAAQ,0BAAsB;AACzE,SACEC,mBAAmB,EACnBC,2BAA2B,EAC3BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,wBAAwB,QACnB,6BAAyB;AAChC,SAASC,uBAAuB,EAAEC,iBAAiB,QAAQ,uBAAmB;AAE9E;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,sBACXxB,wCAAAA,QAAQyB,GAAG,CAAC,2BAA2B,YAAvCzB,wCAA2C,0CAAyC;AAEtF,2CAA2C,GAC3C,OAAO,MAAM0B,uBAAuB,CAAC,eAAe,EAAEF,mBAAmB,CAAC,CAAC,CAAA;AAE3E,OAAO,MAAMG,uBAAuB;IAClCC,cAAc,IAAI,OAAO;IACzB;;;GAGC,GACDC,eAAe,MAAM,OAAO;IAC5BC,cAAc;IACd,uDAAuD,GACvDC,kBAAkB;IAClBC,gBAAgB,MAAM;IACtBC,iBAAiB,IAAI,OAAO;IAC5B,6FAA6F,GAC7FC,aAAa;IACb,gDAAgD,GAChDC,gBAAgB;IAChB,+FAA+F,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,KAAK,QAAQ;YAC9B,4DAA4D;YAC5D,IAAI,CAACD,MAAMK,MAAM,EAAEN,MAAMpI,IAAI,CAACqI,MAAM/H,IAAI;QAC1C,OAAO8H,MAAMpI,IAAI,CAACqI,MAAM/H,IAAI;IAC9B;IACA,OAAO7I,mBAAmB,CAAC,KAAK,EAAE+L,KAAKoD,IAAI,CAAC,2BAA2B,CAAC,EAAEwB,MAAMO,IAAI,CAAC,OAAO;QAAER;IAAS;AACzG"}
@@ -58,6 +58,13 @@ export interface SiteImportCss {
58
58
  index: Map<string, CssRule[]>;
59
59
  /** Families its `@font-face` rules name, in order. */
60
60
  fontFaces: string[];
61
+ /** Read for its dark scheme (AGL-4152): the rules that scheme alone selects, by a media query or a class on the page. */
62
+ darkRules: number;
63
+ }
64
+ /** Which of a page's color schemes a read of its stylesheets answers for. */
65
+ export interface SiteImportCssOptions {
66
+ /** Absent is `light`, as a page is first read. */
67
+ scheme?: 'light' | 'dark';
61
68
  }
62
69
  /** A length in px at the read width; `em`/`rem` at 16. */
63
70
  export declare function siteImportLengthPx(value: string): number | null;
@@ -65,7 +72,7 @@ export declare function siteImportLengthPx(value: string): number | null;
65
72
  * The page's sheets parsed for a wide screen. Malformed CSS is read as far as
66
73
  * it makes sense, as a browser would; nothing throws.
67
74
  */
68
- export declare function siteImportCssOf(sheets: readonly string[], viewport?: number): SiteImportCss;
75
+ export declare function siteImportCssOf(sheets: readonly string[], viewport?: number, options?: SiteImportCssOptions): SiteImportCss;
69
76
  /** One element's resolved style: the kept properties, `var()` read, lowercased. */
70
77
  export type SiteImportComputedStyle = ReadonlyMap<string, string>;
71
78
  /** Reads elements' styles over a page's structure, each once. */