@aglyn/plugins-ai 1.11.0 → 1.13.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 (74) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-media-create.component.js +1 -1
  3. package/src/lib/components/ai-media-create.component.js.map +1 -1
  4. package/src/lib/components/ai-upsell-dialog.component.js +1 -1
  5. package/src/lib/components/ai-upsell-dialog.component.js.map +1 -1
  6. package/src/lib/jobs/ai-job-import-step.d.ts +1 -1
  7. package/src/lib/jobs/ai-job-import-step.js +37 -8
  8. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  9. package/src/lib/jobs/ai-job-privacy-step.js +2 -2
  10. package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
  11. package/src/lib/jobs/ai-site-import-compile.js +27 -37
  12. package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
  13. package/src/lib/jobs/ai-site-import-look.d.ts +19 -4
  14. package/src/lib/jobs/ai-site-import-look.js +162 -46
  15. package/src/lib/jobs/ai-site-import-look.js.map +1 -1
  16. package/src/lib/jobs/ai-theme-brand-inputs.d.ts +12 -0
  17. package/src/lib/jobs/ai-theme-brand-inputs.js +1 -1
  18. package/src/lib/jobs/ai-theme-brand-inputs.js.map +1 -1
  19. package/src/lib/layout-language/ai-layout-compiler.js +7 -1
  20. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  21. package/src/lib/model/ai-credit-estimate.d.ts +15 -0
  22. package/src/lib/model/ai-credit-estimate.js +13 -0
  23. package/src/lib/model/ai-credit-estimate.js.map +1 -1
  24. package/src/lib/model/ai-site-import-fidelity.d.ts +46 -3
  25. package/src/lib/model/ai-site-import-fidelity.js +254 -62
  26. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  27. package/src/lib/model/ai-site-import-report.d.ts +7 -0
  28. package/src/lib/model/ai-site-import-report.js +17 -5
  29. package/src/lib/model/ai-site-import-report.js.map +1 -1
  30. package/src/lib/model/ai-site-import.d.ts +75 -4
  31. package/src/lib/model/ai-site-import.js +34 -11
  32. package/src/lib/model/ai-site-import.js.map +1 -1
  33. package/src/lib/model/ai-site-look.d.ts +16 -0
  34. package/src/lib/model/ai-site-look.js +76 -14
  35. package/src/lib/model/ai-site-look.js.map +1 -1
  36. package/src/lib/model/ai-upsell-copy.js +1 -1
  37. package/src/lib/model/ai-upsell-copy.js.map +1 -1
  38. package/src/lib/site-import/fixtures/aglyn-com-recordings.d.ts +2 -1
  39. package/src/lib/site-import/fixtures/aglyn-com-recordings.js +3 -2
  40. package/src/lib/site-import/fixtures/aglyn-com-recordings.js.map +1 -1
  41. package/src/lib/site-import/fixtures/site-import-crawl-recordings.d.ts +5 -0
  42. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js +116 -3
  43. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js.map +1 -1
  44. package/src/lib/site-import/fixtures/site-import-fidelity-replay.d.ts +7 -0
  45. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +15 -0
  46. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
  47. package/src/lib/site-import/fixtures/site-layout-recordings.d.ts +32 -0
  48. package/src/lib/site-import/fixtures/site-layout-recordings.js +59 -3
  49. package/src/lib/site-import/fixtures/site-layout-recordings.js.map +1 -1
  50. package/src/lib/site-import/fixtures/site-look-slate.d.ts +2 -1
  51. package/src/lib/site-import/fixtures/site-look-slate.js +2 -1
  52. package/src/lib/site-import/fixtures/site-look-slate.js.map +1 -1
  53. package/src/lib/site-import/site-import-crawl.d.ts +9 -1
  54. package/src/lib/site-import/site-import-crawl.js +128 -23
  55. package/src/lib/site-import/site-import-crawl.js.map +1 -1
  56. package/src/lib/site-import/site-import-css.d.ts +89 -1
  57. package/src/lib/site-import/site-import-css.js +468 -28
  58. package/src/lib/site-import/site-import-css.js.map +1 -1
  59. package/src/lib/site-import/site-import-data-forms.d.ts +32 -0
  60. package/src/lib/site-import/site-import-data-forms.js +531 -0
  61. package/src/lib/site-import/site-import-data-forms.js.map +1 -0
  62. package/src/lib/site-import/site-import-html.d.ts +10 -1
  63. package/src/lib/site-import/site-import-html.js +21 -5
  64. package/src/lib/site-import/site-import-html.js.map +1 -1
  65. package/src/lib/site-import/site-import-layout.d.ts +9 -2
  66. package/src/lib/site-import/site-import-layout.js +383 -62
  67. package/src/lib/site-import/site-import-layout.js.map +1 -1
  68. package/src/lib/site-import/site-import-nav.js +17 -3
  69. package/src/lib/site-import/site-import-nav.js.map +1 -1
  70. package/src/lib/site-import/site-import-page.js +5 -0
  71. package/src/lib/site-import/site-import-page.js.map +1 -1
  72. package/src/lib/site-import/site-import-same-page.d.ts +41 -0
  73. package/src/lib/site-import/site-import-same-page.js +108 -0
  74. package/src/lib/site-import/site-import-same-page.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-look.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 BROUGHT IN KEEPS ITS OWN LOOK (AGL-4084).\n *\n * The first wave's look pass, before the header and footer, with no model:\n *\n * - **The theme.** The owner's own home page is read once more as AglynBot,\n * with the edge headers a site this platform serves gets whether or not a\n * caller hands them in (AGL-4108: production handed none, our own edge\n * challenged the read, and the 10/29 site kept the starter's indigo), and\n * the signals a guided start reads off the sites a person likes\n * (AGL-3975: colors, ground, type mood, corners, buttons, cards, header,\n * density, motion) pin the look. What the reader found of the source's\n * look (AGL-4106) pins it closer (AGL-4108): its buttons' fill is the\n * brand and its links' color the accent, its page's ground is the site's,\n * its eyebrows' own color the theme's third and its eyebrows spaced\n * capitals with no line before them (AGL-4138), and its own font family\n * is the site's wherever the theme font catalog has it, else a pairing of\n * its type mood. The look is drawn and saved\n * exactly as a guided start's (`aiSiteStyleFor`, `aiSaveSiteTheme`): a\n * built-in base plus the brand colors and fonts, every color held to the\n * theme's reading checks. A site whose owner already chose a theme keeps\n * it.\n * - **The logo.** The source header's logo, as the source draws it, into the\n * site's media library once: an SVG is turned into a PNG 192 pixels tall\n * (the library takes pictures, not drawings), a picture is kept as it is.\n * - **The listing.** The home page's own title, description and share\n * picture become the site's listing, only while the site still has the\n * listing it was created with: an owner's own words are never written\n * over.\n *\n * Nothing here fails a wave: a source whose look cannot be read keeps the\n * site's theme, and a logo that cannot be brought in leaves the header its\n * name.\n *=========================================*/\n\nimport type { PluginMediaIngest } from '@aglyn/aglyn/plugin-manager/plugin-media-ingest'\nimport { themeFontFacts, type ThemeFontFacts } from '@aglyn/aglyn/plugin-manager/plugin-theme-font-catalog'\nimport { syncHostProjectionForMembers } from '@aglyn/tenant-data-admin/server/host-memberships'\nimport { aiSiteListingSeeded } from '../model/ai-site-entity'\nimport type { AiSiteImportFinish, AiSiteImportHome, AiSiteImportLook, AiSiteImportPhoto, SiteImportLookFacts } from '../model/ai-site-import'\nimport { aiSiteKindFor } from '../model/ai-site-kinds'\nimport { aiHexOklch, aiSiteSeed, aiSiteStyleFor, type AiSiteLookPins, type AiSiteSourceFont, type AiSiteStyle } from '../model/ai-site-look'\nimport { aiSiteIsStarterSrc } from '../model/ai-site-photos'\nimport { AGLYN_BOT_USER_AGENT, siteImportOrigins, type SiteImportCrawlSeams } from '../site-import/site-import-crawl'\nimport { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor, type SiteImportHeadersFor } from '../site-import/site-import-edge'\nimport { bringInSiteImportPhotos, siteImportImageKey, siteImportLogoUrl } from '../site-import/site-import-images'\nimport { aiSaveSiteTheme, aiWorkspaceSiteStyles } from './ai-job-site-look'\nimport { aiSiteInspirationLookPins } from './ai-site-inspiration'\nimport { aiSiteInspirationSignals, type AiSiteInspirationSite } from './ai-site-inspiration-signals'\nimport {\n AI_THEME_BRAND_COLORS_PER_SOURCE,\n AI_THEME_REFERENCE_MAX_BYTES,\n AI_THEME_REFERENCE_STYLESHEETS,\n AI_THEME_STYLESHEET_MAX_BYTES,\n AI_THEME_THEME_COLOR_WEIGHT,\n fetchPublicTextDetailed,\n rankBrandColors,\n stylesheetUrlsOf,\n type AiReferencePage,\n type PublicFetchOptions,\n type PublicFetchResult,\n} from './ai-theme-brand-inputs'\n\n/** The height an SVG logo is drawn at as a picture: crisp at twice the header's 40. */\nexport const AI_SITE_IMPORT_LOGO_HEIGHT = 192\n\n/** The largest logo file read. */\nexport const AI_SITE_IMPORT_LOGO_MAX_BYTES = 1024 * 1024\n\n/** One read's own clock in the look pass. */\nconst LOOK_READ_MS = 8_000\n\ntype Fetch = (url: string, options: PublicFetchOptions) => Promise<PublicFetchResult>\n\n/**\n * The home page and its first stylesheets, read as AglynBot (AGL-4084).\n * `headersFor` is asked for every request and every redirect hop, as the\n * crawl asks it (`aiSiteImportLookHeaders`: the edge header only to the\n * site's own origins). `null` when the page cannot be read.\n */\nexport async function readSiteImportLookPage(\n url: string,\n input: { fetch?: Fetch; headersFor?: SiteImportHeadersFor | null; signal?: AbortSignal },\n): Promise<AiReferencePage | null> {\n const fetchText = input.fetch ?? fetchPublicTextDetailed\n const headersFor = input.headersFor ?? null\n const read = (address: string, maxBytes: number, accept: RegExp) =>\n fetchText(address, {\n maxBytes,\n accept,\n userAgent: AGLYN_BOT_USER_AGENT,\n timeoutMs: LOOK_READ_MS,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(headersFor ? { headersFor } : {}),\n }).catch(() => null)\n const page = await read(url, AI_THEME_REFERENCE_MAX_BYTES, /text\\/html|application\\/xhtml\\+xml/i)\n if (!page?.ok) return null\n const stylesheets: string[] = []\n for (const sheet of stylesheetUrlsOf(page.text, page.url).slice(0, AI_THEME_REFERENCE_STYLESHEETS)) {\n const css = await read(sheet, AI_THEME_STYLESHEET_MAX_BYTES, /text\\/css/i)\n if (css?.ok) stylesheets.push(css.text)\n }\n return { url: page.url, html: page.text, stylesheets }\n}\n\nconst SOLID_HEX = /(?<!&)#(?:[0-9a-f]{6}|[0-9a-f]{3})(?![0-9a-z])/gi\nconst SOLID_RGB = /rgba?\\(\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})\\s*(?:[,/]\\s*([\\d.]+%?)\\s*)?\\)/gi\nconst THEME_COLOR = /<meta\\b[^>]*\\bname\\s*=\\s*[\"']?theme-color\\b[^>]*\\bcontent\\s*=\\s*[\"']?\\s*(#[0-9a-f]{3,6})/gi\n\nconst hexOf = (value: string): string | null => {\n const raw = value.trim().toLowerCase()\n if (/^#[0-9a-f]{6}$/.test(raw)) return raw\n if (/^#[0-9a-f]{3}$/.test(raw)) return `#${raw[1]}${raw[1]}${raw[2]}${raw[2]}${raw[3]}${raw[3]}`\n return null\n}\n\n/**\n * A source's brand colors as it DRAWS them (AGL-4084): the colors its markup\n * and stylesheets use solid, most used first, the colorful before the greys.\n * A translucent color is a tint of one (a hover, a focus ring), never a use\n * of it, so it is not counted: aglyn.com's focus rings, a light blue at a\n * quarter strength, outnumbered the deep blue its buttons and links are\n * drawn in, which the theme reader would otherwise take as its brand.\n */\nexport function aiSiteImportBrandColors(page: Pick<AiReferencePage, 'html' | 'stylesheets'>): string[] {\n const weights = new Map<string, number>()\n const add = (hex: string | null, weight = 1) => {\n if (hex) weights.set(hex, (weights.get(hex) ?? 0) + weight)\n }\n for (const match of page.html.matchAll(THEME_COLOR)) add(hexOf(match[1] ?? ''), AI_THEME_THEME_COLOR_WEIGHT)\n for (const text of [page.html, ...page.stylesheets]) {\n for (const match of text.matchAll(SOLID_HEX)) add(hexOf(match[0]))\n for (const match of text.matchAll(SOLID_RGB)) {\n const alpha = match[4]\n if (alpha !== undefined && (alpha.endsWith('%') ? Number(alpha.slice(0, -1)) < 100 : Number(alpha) < 1)) continue\n const channels = [match[1], match[2], match[3]].map((value) => Math.min(255, Number(value)))\n add(`#${channels.map((value) => value.toString(16).padStart(2, '0')).join('')}`)\n }\n }\n return rankBrandColors(weights, AI_THEME_BRAND_COLORS_PER_SOURCE)\n}\n\n/** How colorful a color must be to carry a brand: the inspiration reader's own floor. */\nconst COLORFUL_CHROMA = 0.04\n\nconst colorful = (hex: string | null | undefined): hex is string => !!hex && /^#[0-9a-f]{6}$/i.test(hex) && aiHexOklch(hex).C >= COLORFUL_CHROMA\n\n/**\n * The brand and accent a source's look facts give (AGL-4108): the fill of\n * its filled buttons as the brand, the color of its links as the accent\n * where it is a color of its own, and the reverse where its buttons are not\n * colorful. The theme draws the brand at the nearest shade of it that reads\n * (`aiSiteColors`): aglyn.com's light blue buttons, under white words at\n * 2.4:1, come out at the deeper blue of its own links.\n */\nexport function aiSiteImportBrandOf(facts: Pick<SiteImportLookFacts, 'buttonFill' | 'link'> | null | undefined): { brand: string; accent: string | null } | null {\n const fill = colorful(facts?.buttonFill) ? (facts?.buttonFill as string).toLowerCase() : null\n const link = colorful(facts?.link) ? (facts?.link as string).toLowerCase() : null\n const brand = fill ?? link\n if (!brand) return null\n return { brand, accent: link && link !== brand ? link : null }\n}\n\nconst solidHex = (value: string | null | undefined): string | null => (value && /^#[0-9a-f]{6}$/i.test(value) ? value.toLowerCase() : null)\n\n/**\n * The look a source's signals pin (AGL-4084), drawn the way a guided start's\n * is: the kind of site its own description says, the import's seed, its\n * strongest color as the brand. What the reader found of its look\n * (`facts`, AGL-4108) pins it closer: its buttons' fill as the brand and its\n * links' color as the accent, its eyebrows' own color as the third, and its\n * own fonts where the catalog has them (`fonts`). `null` where the source\n * showed no color to carry a brand, so the site keeps the theme it has.\n *\n * How the owner asked the site to be finished (AGL-4152) says what else:\n * - **Keep my site** (`keep`, and an import that names none) pins the rest\n * of its look as it draws it: its page's ground and its dark bands', its\n * buttons' corners and case and their own fill and words, every inspiration\n * signal, and its eyebrows set as spaced capitals.\n * - **Improve it** (`improve`) pins only the brand, accent and third colors\n * and the fonts, so the base that suits the kind of site shows with its own\n * corners, buttons, grounds and eyebrows.\n */\nexport function aiSiteImportStyle(\n site: AiSiteInspirationSite | null,\n input: {\n seed: number\n description: string\n avoid?: readonly AiSiteStyle[]\n facts?: SiteImportLookFacts | null\n fonts?: AiSiteStyle['sourceFonts']\n finish?: AiSiteImportFinish | null\n },\n): AiSiteStyle | null {\n const facts = input.facts ?? null\n const finish: AiSiteImportFinish = input.finish === 'improve' ? 'improve' : 'keep'\n const own = aiSiteImportBrandOf(facts)\n if (!site && !own) return null\n const kind = aiSiteKindFor(input.description)\n const signals = site ? aiSiteInspirationLookPins({ v: 1, sites: [site], unread: 0 }, { kind, seed: input.seed }) : {}\n // Improve keeps the brand's colors and its type, and nothing else its source draws.\n const pins: AiSiteLookPins =\n finish === 'improve'\n ? {\n ...(signals.brand ? { brand: signals.brand } : {}),\n ...(signals.hue !== undefined ? { hue: signals.hue } : {}),\n ...(signals.accent !== undefined ? { accent: signals.accent } : {}),\n ...(signals.fonts ? { fonts: signals.fonts } : {}),\n }\n : signals\n if (own) {\n pins.brand = own.brand\n pins.hue = Math.round(aiHexOklch(own.brand).h) % 360\n if (own.accent) pins.accent = Math.round(aiHexOklch(own.accent).h) % 360\n }\n // Its buttons' corners round the theme's shape where its stylesheets did not say (AGL-4108).\n const radius = facts?.buttonRadius\n if (finish === 'keep' && typeof radius === 'number' && Number.isFinite(radius) && radius >= 0) {\n pins.buttons ??= radius >= 24 ? 'pill' : radius <= 2 ? 'square' : 'rounded'\n pins.corners ??= radius <= 2 ? 'sharp' : radius <= 10 ? 'soft' : radius <= 20 ? 'round' : 'pill'\n }\n // Its eyebrows as it sets them (AGL-4138): spaced capitals with no line before them — the\n // reader takes an eyebrow only in capitals, and no mark a page draws before one is a word of\n // it — and their own color, where it is one, as the theme's third.\n if (facts && finish === 'keep') pins.eyebrow = 'caps'\n if (colorful(facts?.eyebrow)) pins.tertiary = (facts?.eyebrow as string).toLowerCase()\n if (!pins.brand) return null\n const style = aiSiteStyleFor({ kind, answer: {}, seed: input.seed, brand: pins.brand, avoid: input.avoid ?? [], pins })\n const fonts = input.fonts ? { sourceFonts: input.fonts } : {}\n if (finish === 'improve') return { ...style, finish, ...fonts }\n // Keep my site (AGL-4152): its grounds, its buttons' case, and its filled buttons as it draws them.\n const page = solidHex(facts?.background)\n const darkPage = solidHex(facts?.darkBackground)\n const buttonFill = solidHex(facts?.buttonFill)\n const buttonText = buttonFill ? solidHex(facts?.buttonText) : null\n const buttonCase = facts?.buttonCase === 'upper' || facts?.buttonCase === 'none' ? facts.buttonCase : null\n return {\n ...style,\n finish,\n ...(page ? { page } : {}),\n ...(darkPage ? { darkPage } : {}),\n ...(buttonCase ? { buttonCase } : {}),\n ...(buttonFill ? { buttonFill } : {}),\n ...(buttonText ? { buttonText } : {}),\n ...fonts,\n }\n}\n\n/** A family's facts, as the theme font catalog answers them. */\nexport type AiSiteImportFontFacts = (family: string) => Promise<ThemeFontFacts | undefined>\n\n/**\n * The source's own fonts (AGL-4108), each where the theme font catalog has\n * the family (Google Fonts', as the fonts plugin registers it), or the\n * source loads it from Google Fonts itself: its body's and its headings'.\n * `null` where its body's family is neither, and the pairing of the source's\n * type mood sets the site instead.\n */\nexport async function aiSiteImportSourceFonts(\n facts: Pick<SiteImportLookFacts, 'fonts'> | null | undefined,\n lookup: AiSiteImportFontFacts = themeFontFacts,\n): Promise<AiSiteStyle['sourceFonts']> {\n const fonts = facts?.fonts\n if (!fonts?.body) return null\n const loaded = new Set(fonts.google.map((family) => family.toLowerCase()))\n const resolve = async (family: string | null): Promise<AiSiteSourceFont | null> => {\n if (!family) return null\n const known = await lookup(family).catch(() => undefined)\n if (known) return { family: known.family, category: known.category, weights: [...known.weights] }\n return loaded.has(family.toLowerCase()) ? { family, category: 'sans-serif', weights: [] } : null\n }\n const body = await resolve(fonts.body)\n if (!body) return null\n const heading = fonts.headings && fonts.headings.toLowerCase() !== body.family.toLowerCase() ? await resolve(fonts.headings) : null\n return { body, heading }\n}\n\n/**\n * The site's listing in the home page's own words (AGL-4084), as field\n * paths: its title and description each only where the site still has the\n * one it was created with, so an owner's own listing is never written over.\n * `{}` with nothing to write.\n */\nexport function aiSiteImportListingUpdates(seo: unknown, displayName: unknown, home: Pick<AiSiteImportHome, 'title' | 'description'>): Record<string, string> {\n const seeded = aiSiteListingSeeded(seo, displayName)\n const current = (seo && typeof seo === 'object' ? seo : {}) as Record<string, unknown>\n const updates: Record<string, string> = {}\n const title = home.title.replace(/\\s+/g, ' ').trim()\n const description = home.description.replace(/\\s+/g, ' ').trim()\n if (title && seeded.title && title !== current['title']) updates['seo.title'] = title\n if (description && seeded.description && description !== current['description']) updates['seo.description'] = description\n return updates\n}\n\n/** Whether the site's share picture is still open: none, or the starter's (AGL-3988). */\nfunction shareOpen(seo: unknown): boolean {\n const image = (seo as { image?: unknown } | null | undefined)?.image\n if (image === undefined || image === null) return true\n return typeof image === 'string' && (!image.trim() || aiSiteIsStarterSrc(image))\n}\n\n/** Turns an SVG drawing into a PNG of a height; `null` where it cannot. */\nexport type AiSiteImportRasterize = (svg: Uint8Array, height: number) => Promise<Uint8Array | null>\n\nexport interface AiSiteImportLookDeps {\n fetch?: Fetch\n /** The edge headers for the source, asked with its domain; absent, the edge is asked as the crawl asks it (AGL-4108). */\n headersFor?: SiteImportCrawlSeams['headersFor']\n /** The edge's own answer, per address (`siteImportEdgeHeadersFor`), where no `headersFor` is given. */\n edgeHeadersFor?: typeof siteImportEdgeHeadersFor\n /** A family's facts in the theme font catalog (`themeFontFacts`). */\n fontFacts?: AiSiteImportFontFacts\n save?: typeof aiSaveSiteTheme\n others?: typeof aiWorkspaceSiteStyles\n ingest?: PluginMediaIngest | null\n rasterize?: AiSiteImportRasterize\n /** The site's document, as the listing reads it. */\n readHost?: (firestore: FirebaseFirestore.Firestore, hostId: string) => Promise<Record<string, unknown> | null>\n writeHost?: (firestore: FirebaseFirestore.Firestore, hostId: string, updates: Record<string, unknown>) => Promise<void>\n /** Re-fans the rows every site list reads a site's icon from (AGL-3972), after the look sets one. */\n syncMemberships?: (orgId: string, hostId: string) => Promise<void>\n}\n\n/** The most pictures the home page's menus bring into the library (AGL-4139). */\nexport const AI_SITE_IMPORT_MENU_PICTURES = 4\n\n/** The pictures the home page's menus show (AGL-4139), each once, the first few: a featured card's. */\nexport function aiSiteImportMenuPictures(home: Pick<AiSiteImportHome, 'nav'>): Array<{ url: string; alt: string }> {\n const seen = new Set<string>()\n const out: Array<{ url: string; alt: string }> = []\n for (const group of home.nav?.items ?? []) {\n for (const column of group.columns ?? []) {\n if (!column.image || seen.has(column.image.url) || out.length >= AI_SITE_IMPORT_MENU_PICTURES) continue\n seen.add(column.image.url)\n out.push({ url: column.image.url, alt: column.image.alt })\n }\n }\n return out\n}\n\n/** Whether the site still has no icon of its own (AGL-4139): an owner's is never written over. */\nfunction faviconOpen(seo: unknown): boolean {\n const favicon = (seo as { favicon?: unknown } | null | undefined)?.favicon\n return favicon === undefined || favicon === null || (typeof favicon === 'string' && !favicon.trim())\n}\n\n\nexport interface AiSiteImportLookInput {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n orgId: string\n /** The member the logo and the share picture are stored as. */\n uid: string\n /** The import job's id, which the look's seed is drawn from. */\n jobId: string\n domain: string\n home: AiSiteImportHome\n at: string\n signal?: AbortSignal\n /** How the site is finished (AGL-4152): Keep my site keeps more of the source's look. Absent is `keep`. */\n finish?: AiSiteImportFinish | null\n}\n\nasync function readHostDoc(firestore: FirebaseFirestore.Firestore, hostId: string): Promise<Record<string, unknown> | null> {\n const snapshot = await firestore.collection('hosts').doc(hostId).get()\n return snapshot.exists ? ((snapshot.data() ?? {}) as Record<string, unknown>) : null\n}\n\nasync function writeHostDoc(firestore: FirebaseFirestore.Firestore, hostId: string, updates: Record<string, unknown>): Promise<void> {\n await firestore.collection('hosts').doc(hostId).update(updates)\n}\n\n/** Turns an SVG into a PNG in this process, where `sharp` is shipped; `null` where it is not. */\nasync function rasterizeHere(svg: Uint8Array, height: number): Promise<Uint8Array | null> {\n const images = await import('./ai-image-reads')\n const origin = images.aiImageReadsOrigin()\n if (origin) return images.requestAiLogoRaster(origin, svg, height)\n return images.rasterizeAiLogoSvg(svg, height)\n}\n\n/**\n * The source header's logo in the site's library (AGL-4084), once: the copy\n * a page already brought in is reused by its key. An SVG becomes a PNG.\n * `null` where it cannot be brought in, and the header then prints the name.\n */\nexport async function aiSiteImportLogo(\n input: { hostId: string; uid: string; domain: string; logo: NonNullable<AiSiteImportHome['brand']['logo']>; alt: string; headersFor?: SiteImportHeadersFor | null; signal?: AbortSignal },\n deps: { fetch?: Fetch; ingest: PluginMediaIngest | null; rasterize?: AiSiteImportRasterize },\n): Promise<AiSiteImportPhoto | null> {\n const ingest = deps.ingest\n const url = siteImportLogoUrl(input.logo.url)\n if (!ingest?.findImportedPhoto || !url) return null\n const sourceKey = siteImportImageKey(url)\n try {\n const held = await ingest.findImportedPhoto({ hostId: input.hostId, sourceKey })\n if (held) return { mediaId: held.mediaId, src: held.src, alt: input.alt, from: url, ...(held.width ? { width: held.width } : {}), ...(held.height ? { height: held.height } : {}) }\n const fetched = await (deps.fetch ?? fetchPublicTextDetailed)(url, {\n maxBytes: AI_SITE_IMPORT_LOGO_MAX_BYTES,\n accept: /^image\\//i,\n acceptHeader: 'image/svg+xml,image/png,image/webp,image/jpeg;q=0.9',\n userAgent: AGLYN_BOT_USER_AGENT,\n timeoutMs: LOOK_READ_MS,\n refuseOver: true,\n binary: true,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.headersFor ? { headersFor: input.headersFor } : {}),\n })\n if (!fetched.ok || !fetched.data?.byteLength) return null\n const type = fetched.contentType.split(';')[0].trim().toLowerCase()\n let bytes: Uint8Array | null = fetched.data\n let contentType = type\n if (type === 'image/svg+xml' || input.logo.type === 'svg') {\n bytes = await (deps.rasterize ?? rasterizeHere)(fetched.data, AI_SITE_IMPORT_LOGO_HEIGHT).catch(() => null)\n contentType = 'image/png'\n } else if (!/^image\\/(?:png|jpeg|webp|gif)$/.test(type)) {\n return null\n }\n if (!bytes?.byteLength) return null\n const stored = await ingest.ingest({\n hostId: input.hostId,\n uid: input.uid,\n fileName: `logo.${contentType === 'image/jpeg' ? 'jpg' : contentType.split('/')[1]}`,\n contentType,\n bytes,\n ...(input.alt ? { alt: input.alt.slice(0, 250) } : {}),\n importedFrom: { key: sourceKey, url, domain: input.domain },\n })\n if (!stored.ok) return null\n return { mediaId: stored.mediaId, src: stored.src, alt: input.alt, from: url, ...(stored.width ? { width: stored.width } : {}), ...(stored.height ? { height: stored.height } : {}) }\n } catch (error) {\n console.warn('[site-import] the logo could not be brought in', { hostId: input.hostId, error })\n return null\n }\n}\n\n/** The look pass (AGL-4084): the theme, the logo and the listing, from the owner's own home page. No model. */\nexport async function aiRunSiteImportLook(input: AiSiteImportLookInput, deps: AiSiteImportLookDeps = {}): Promise<AiSiteImportLook> {\n const { firestore, hostId, home } = input\n const headersFor = await aiSiteImportLookHeaders(input.domain, deps)\n const seed = aiSiteSeed(input.jobId)\n const page = await readSiteImportLookPage(home.url, { ...(deps.fetch ? { fetch: deps.fetch } : {}), headersFor, ...(input.signal ? { signal: input.signal } : {}) })\n // The source's own signals, its brand colors as it draws them solid.\n const signals = page ? aiSiteInspirationSignals(page) : null\n const site = signals && page ? { ...signals, colors: aiSiteImportBrandColors(page) } : signals\n const avoid = await (deps.others ?? aiWorkspaceSiteStyles)(firestore, { orgId: input.orgId, hostId })\n // What the reader found of its look, its buttons, ground and fonts (AGL-4108).\n const facts = home.look ?? null\n const fonts = await aiSiteImportSourceFonts(facts, deps.fontFacts)\n const style = aiSiteImportStyle(site, { seed, description: `${home.siteName} ${home.description}`, avoid, facts, fonts, finish: input.finish ?? null })\n let theme: AiSiteImportLook['theme'] = 'unread'\n if (style) {\n const saved = await (deps.save ?? aiSaveSiteTheme)(firestore, { hostId, jobId: input.jobId, style })\n if (saved.write === 'missing') throw new Error(`site ${hostId} vanished while its look was brought in`)\n theme = saved.write === 'kept' ? 'kept' : 'applied'\n }\n const ingest = deps.ingest ?? null\n const logo = home.brand.logo\n ? await aiSiteImportLogo(\n { hostId, uid: input.uid, domain: input.domain, logo: home.brand.logo, alt: home.siteName || home.brand.text, headersFor, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}), ...(deps.rasterize ? { rasterize: deps.rasterize } : {}) },\n )\n : null\n // The pictures its menus show, in the library like its pages' photos (AGL-4139), for the header's panels.\n const menuImages = aiSiteImportMenuPictures(home)\n const pictures = menuImages.length\n ? (\n await bringInSiteImportPhotos(\n { hostId, uid: input.uid, domain: input.domain, images: menuImages, deadlineAt: Date.now() + LOOK_READ_MS, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}) },\n )\n ).assets\n : []\n // The site's listing in its own words, only over the one it was created with.\n let seo = false\n const host = await (deps.readHost ?? readHostDoc)(firestore, hostId)\n if (host) {\n const updates: Record<string, unknown> = aiSiteImportListingUpdates(host['seo'], host['displayName'], home)\n // The site's icon from the one its head names, where the site has none (AGL-4139).\n if (home.favicon && faviconOpen(host['seo'])) {\n const icon = await bringInSiteImportPhotos(\n { hostId, uid: input.uid, domain: input.domain, images: [{ url: home.favicon, alt: '' }], deadlineAt: Date.now() + LOOK_READ_MS, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}) },\n )\n const photo = icon.assets[0]\n if (photo) updates['seo.favicon'] = photo.src\n }\n if (home.ogImage && shareOpen(host['seo'])) {\n const share = await bringInSiteImportPhotos(\n { hostId, uid: input.uid, domain: input.domain, images: [{ url: home.ogImage, alt: '' }], deadlineAt: Date.now() + LOOK_READ_MS, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}) },\n )\n const photo = share.assets[0]\n if (photo) {\n updates['seo.image'] = photo.src\n if (photo.width) updates['seo.imageWidth'] = photo.width\n if (photo.height) updates['seo.imageHeight'] = photo.height\n }\n }\n if (Object.keys(updates).length) {\n await (deps.writeHost ?? writeHostDoc)(firestore, hostId, updates)\n seo = true\n // Every site list reads the icon the members' rows carry (AGL-3972).\n if (updates['seo.favicon']) {\n await (deps.syncMemberships ?? syncHostProjectionForMembers)(input.orgId, hostId).catch((error: unknown) => {\n console.warn('[site-import] the site lists were not told of the new icon', { hostId, error })\n })\n }\n }\n }\n const drawn = style\n ? {\n ...(typeof style.headerAlign === 'string' ? { headerAlign: style.headerAlign } : {}),\n ...(typeof style.rhythm === 'string' ? { rhythm: style.rhythm } : {}),\n ...(typeof style.motion === 'string' ? { motion: style.motion } : {}),\n }\n : null\n const colors = [...new Set([...(facts ? [facts.buttonFill, facts.link, facts.eyebrow].filter(colorful).map((hex) => hex.toLowerCase()) : []), ...(site?.colors ?? [])])]\n return { at: input.at, theme, colors, logo, ...(pictures.length ? { pictures } : {}), seo, seed: style ? style.seed : seed, style: drawn }\n}\n\n/**\n * The headers the look's reads of the source go with, per address (AGL-4108),\n * exactly as the crawl's (`siteRequestHeaders`): the caller's where it hands\n * them in, else the edge's own, so a site this platform serves is read past\n * its challenge however the step was registered; and nothing for any address\n * off the site's two origins, a redirect hop's included. Never throws.\n *\n * The 10/29 look read went without the header twice over: no caller handed\n * one in, and the read passed headers the fetch does not take, which is why\n * this is a function the fetch asks for every hop (`headersFor`).\n */\nexport async function aiSiteImportLookHeaders(\n domain: string,\n deps: Pick<AiSiteImportLookDeps, 'headersFor' | 'edgeHeadersFor'>,\n): Promise<SiteImportHeadersFor> {\n const origins = siteImportOrigins(domain)\n let inner: SiteImportHeadersFor = NO_SITE_IMPORT_HEADERS\n try {\n if (deps.headersFor) {\n const headers = await deps.headersFor(domain)\n if (headers && Object.keys(headers).length) inner = () => headers\n } else {\n inner = await (deps.edgeHeadersFor ?? siteImportEdgeHeadersFor)(origins)\n }\n } catch (error) {\n console.warn('[site-import] the edge headers could not be read; reading the look without them', { domain, error })\n }\n return (url: URL) => (origins.includes(url.origin) ? inner(url) : {})\n}\n"],"names":["themeFontFacts","syncHostProjectionForMembers","aiSiteListingSeeded","aiSiteKindFor","aiHexOklch","aiSiteSeed","aiSiteStyleFor","aiSiteIsStarterSrc","AGLYN_BOT_USER_AGENT","siteImportOrigins","NO_SITE_IMPORT_HEADERS","siteImportEdgeHeadersFor","bringInSiteImportPhotos","siteImportImageKey","siteImportLogoUrl","aiSaveSiteTheme","aiWorkspaceSiteStyles","aiSiteInspirationLookPins","aiSiteInspirationSignals","AI_THEME_BRAND_COLORS_PER_SOURCE","AI_THEME_REFERENCE_MAX_BYTES","AI_THEME_REFERENCE_STYLESHEETS","AI_THEME_STYLESHEET_MAX_BYTES","AI_THEME_THEME_COLOR_WEIGHT","fetchPublicTextDetailed","rankBrandColors","stylesheetUrlsOf","AI_SITE_IMPORT_LOGO_HEIGHT","AI_SITE_IMPORT_LOGO_MAX_BYTES","LOOK_READ_MS","readSiteImportLookPage","url","input","fetchText","fetch","headersFor","read","address","maxBytes","accept","userAgent","timeoutMs","signal","catch","page","ok","stylesheets","sheet","text","slice","css","push","html","SOLID_HEX","SOLID_RGB","THEME_COLOR","hexOf","value","raw","trim","toLowerCase","test","aiSiteImportBrandColors","match","weights","Map","add","hex","weight","set","get","matchAll","alpha","undefined","endsWith","Number","channels","map","Math","min","toString","padStart","join","COLORFUL_CHROMA","colorful","C","aiSiteImportBrandOf","facts","fill","buttonFill","link","brand","accent","solidHex","aiSiteImportStyle","site","finish","own","kind","description","signals","v","sites","unread","seed","pins","hue","fonts","round","h","radius","buttonRadius","isFinite","buttons","corners","eyebrow","tertiary","style","answer","avoid","sourceFonts","background","darkPage","darkBackground","buttonText","buttonCase","aiSiteImportSourceFonts","lookup","body","loaded","Set","google","family","resolve","known","category","has","heading","headings","aiSiteImportListingUpdates","seo","displayName","home","seeded","current","updates","title","replace","shareOpen","image","AI_SITE_IMPORT_MENU_PICTURES","aiSiteImportMenuPictures","seen","out","group","nav","items","column","columns","length","alt","faviconOpen","favicon","readHostDoc","firestore","hostId","snapshot","collection","doc","exists","data","writeHostDoc","update","rasterizeHere","svg","height","images","origin","aiImageReadsOrigin","requestAiLogoRaster","rasterizeAiLogoSvg","aiSiteImportLogo","deps","ingest","logo","findImportedPhoto","sourceKey","fetched","held","mediaId","src","from","width","acceptHeader","refuseOver","binary","byteLength","type","contentType","split","bytes","rasterize","stored","uid","fileName","importedFrom","key","domain","error","console","warn","aiRunSiteImportLook","aiSiteImportLookHeaders","jobId","colors","others","orgId","look","fontFacts","siteName","theme","saved","save","write","Error","menuImages","pictures","deadlineAt","Date","now","assets","host","readHost","icon","photo","ogImage","share","Object","keys","writeHost","syncMemberships","drawn","headerAlign","rhythm","motion","filter","at","origins","inner","headers","edgeHeadersFor","includes"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAiC2C;AAG3C,SAASA,cAAc,QAA6B,wDAAuD;AAC3G,SAASC,4BAA4B,QAAQ,mDAAkD;AAC/F,SAASC,mBAAmB,QAAQ,6BAAyB;AAE7D,SAASC,aAAa,QAAQ,4BAAwB;AACtD,SAASC,UAAU,EAAEC,UAAU,EAAEC,cAAc,QAAsE,2BAAuB;AAC5I,SAASC,kBAAkB,QAAQ,6BAAyB;AAC5D,SAASC,oBAAoB,EAAEC,iBAAiB,QAAmC,sCAAkC;AACrH,SAASC,sBAAsB,EAAEC,wBAAwB,QAAmC,qCAAiC;AAC7H,SAASC,uBAAuB,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,uCAAmC;AAClH,SAASC,eAAe,EAAEC,qBAAqB,QAAQ,wBAAoB;AAC3E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,wBAAwB,QAAoC,mCAA+B;AACpG,SACEC,gCAAgC,EAChCC,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I;QACF,IAAI4K,KAAKnJ,UAAU,EAAE;YACnB,MAAMsN,UAAU,MAAMnE,KAAKnJ,UAAU,CAAC4K;YACtC,IAAI0C,WAAWZ,OAAOC,IAAI,CAACW,SAAS1F,MAAM,EAAEyF,QAAQ,IAAMC;QAC5D,OAAO;gBACUnE;YAAfkE,QAAQ,MAAM,EAAClE,uBAAAA,KAAKoE,cAAc,YAAnBpE,uBAAuB3K,0BAA0B4O;QAClE;IACF,EAAE,OAAOvC,OAAO;QACdC,QAAQC,IAAI,CAAC,mFAAmF;YAAEH;YAAQC;QAAM;IAClH;IACA,OAAO,CAACjL,MAAcwN,QAAQI,QAAQ,CAAC5N,IAAIkJ,MAAM,IAAIuE,MAAMzN,OAAO,CAAC;AACrE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-look.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 BROUGHT IN KEEPS ITS OWN LOOK (AGL-4084).\n *\n * The first wave's look pass, before the header and footer, with no model:\n *\n * - **The theme.** The owner's own home page is read once more as AglynBot,\n * with the edge headers a site this platform serves gets whether or not a\n * caller hands them in (AGL-4108: production handed none, our own edge\n * challenged the read, and the 10/29 site kept the starter's indigo), and\n * the signals a guided start reads off the sites a person likes\n * (AGL-3975: colors, ground, type mood, corners, buttons, cards, header,\n * density, motion) pin the look. What the reader found of the source's\n * look (AGL-4106) pins it closer (AGL-4108): its buttons' fill is the\n * brand and its links' color the accent, its page's ground is the site's,\n * its eyebrows' own color the theme's third and its eyebrows spaced\n * capitals with no line before them (AGL-4138), and its own font family\n * is the site's wherever the theme font catalog has it, else a pairing of\n * its type mood. The look is drawn and saved\n * exactly as a guided start's (`aiSiteStyleFor`, `aiSaveSiteTheme`): a\n * built-in base plus the brand colors and fonts, every color held to the\n * theme's reading checks. A site whose owner already chose a theme keeps\n * it.\n * - **The logo.** The source header's logo, as the source draws it, into the\n * site's media library once: an SVG is turned into a PNG 192 pixels tall\n * (the library takes pictures, not drawings), a picture is kept as it is.\n * - **The listing.** The home page's own title, description and share\n * picture become the site's listing, only while the site still has the\n * listing it was created with: an owner's own words are never written\n * over.\n *\n * A bare read never leaves the stock theme (AGL-4152). A source with no color\n * of its own to read (no colorful button, link or declared palette) takes its brand from its logo's dominant colorful hue, then its hero photo's,\n * read from the library's copy. With no picture to read either, what its\n * stylesheets use most decides, and with none of that the site still gets the\n * seed's own look for its kind of site, as a guided start with no answer does,\n * and the look says so (`from`). An owner's chosen theme is still kept.\n *\n * Nothing here fails a wave: a logo that cannot be brought in leaves the header\n * its name.\n *=========================================*/\n\nimport type { PluginMediaIngest } from '@aglyn/aglyn/plugin-manager/plugin-media-ingest'\nimport { themeFontFacts, type ThemeFontFacts } from '@aglyn/aglyn/plugin-manager/plugin-theme-font-catalog'\nimport { syncHostProjectionForMembers } from '@aglyn/tenant-data-admin/server/host-memberships'\nimport { aiSiteListingSeeded } from '../model/ai-site-entity'\nimport type { AiSiteImportFinish, AiSiteImportHome, AiSiteImportLook, AiSiteImportLookFrom, AiSiteImportPhoto, SiteImportLookFacts } from '../model/ai-site-import'\nimport { aiSiteKindFor } from '../model/ai-site-kinds'\nimport { aiHexOklch, aiSiteSeed, aiSiteStyleFor, type AiSiteLookPins, type AiSiteSourceFont, type AiSiteStyle } from '../model/ai-site-look'\nimport { aiSiteIsStarterSrc } from '../model/ai-site-photos'\nimport { AGLYN_BOT_USER_AGENT, siteImportOrigins, type SiteImportCrawlSeams } from '../site-import/site-import-crawl'\nimport { siteImportReadStylesheets } from '../site-import/site-import-css'\nimport { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor, type SiteImportHeadersFor } from '../site-import/site-import-edge'\nimport { siteImportStylesheetLinks } from '../site-import/site-import-html'\nimport { bringInSiteImportPhotos, siteImportImageKey, siteImportLogoUrl } from '../site-import/site-import-images'\nimport { aiSaveSiteTheme, aiWorkspaceSiteStyles } from './ai-job-site-look'\nimport { aiSiteInspirationLookPins } from './ai-site-inspiration'\nimport { aiSiteInspirationSignals, type AiSiteInspirationSite } from './ai-site-inspiration-signals'\nimport {\n AI_THEME_BRAND_COLORS_PER_SOURCE,\n AI_THEME_REFERENCE_MAX_BYTES,\n AI_THEME_THEME_COLOR_WEIGHT,\n fetchPublicTextDetailed,\n logoMediaLocation,\n rankBrandColors,\n readLogoColors,\n type AiReferencePage,\n type PublicFetchOptions,\n type PublicFetchResult,\n} from './ai-theme-brand-inputs'\n\n/** The height an SVG logo is drawn at as a picture: crisp at twice the header's 40. */\nexport const AI_SITE_IMPORT_LOGO_HEIGHT = 192\n\n/** The largest logo file read. */\nexport const AI_SITE_IMPORT_LOGO_MAX_BYTES = 1024 * 1024\n\n/** One read's own clock in the look pass. */\nconst LOOK_READ_MS = 8_000\n\n/** The clock on starting the home page's stylesheets' reads: however many it links, a pass waits no longer than this and one read's own. */\nconst LOOK_SHEETS_MS = 12_000\n\ntype Fetch = (url: string, options: PublicFetchOptions) => Promise<PublicFetchResult>\n\n/**\n * The home page and its stylesheets, every one to the crawl's byte budget\n * (AGL-4152), read as AglynBot (AGL-4084).\n * `headersFor` is asked for every request and every redirect hop, as the\n * crawl asks it (`aiSiteImportLookHeaders`: the edge header only to the\n * site's own origins). `null` when the page cannot be read.\n */\nexport async function readSiteImportLookPage(\n url: string,\n input: { fetch?: Fetch; headersFor?: SiteImportHeadersFor | null; signal?: AbortSignal },\n): Promise<AiReferencePage | null> {\n const fetchText = input.fetch ?? fetchPublicTextDetailed\n const headersFor = input.headersFor ?? null\n const read = (address: string, maxBytes: number, accept: RegExp) =>\n fetchText(address, {\n maxBytes,\n accept,\n userAgent: AGLYN_BOT_USER_AGENT,\n timeoutMs: LOOK_READ_MS,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(headersFor ? { headersFor } : {}),\n }).catch(() => null)\n const page = await read(url, AI_THEME_REFERENCE_MAX_BYTES, /text\\/html|application\\/xhtml\\+xml/i)\n if (!page?.ok) return null\n const startedAt = Date.now()\n const stylesheets = await siteImportReadStylesheets(siteImportStylesheetLinks(page.text, page.url), (sheet, maxBytes) => read(sheet, maxBytes, /text\\/css|text\\/plain/i), {\n outOfTime: () => Date.now() - startedAt >= LOOK_SHEETS_MS,\n })\n return { url: page.url, html: page.text, stylesheets }\n}\n\nconst SOLID_HEX = /(?<!&)#(?:[0-9a-f]{6}|[0-9a-f]{3})(?![0-9a-z])/gi\nconst SOLID_RGB = /rgba?\\(\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})\\s*(?:[,/]\\s*([\\d.]+%?)\\s*)?\\)/gi\nconst THEME_COLOR = /<meta\\b[^>]*\\bname\\s*=\\s*[\"']?theme-color\\b[^>]*\\bcontent\\s*=\\s*[\"']?\\s*(#[0-9a-f]{3,6})/gi\n\nconst hexOf = (value: string): string | null => {\n const raw = value.trim().toLowerCase()\n if (/^#[0-9a-f]{6}$/.test(raw)) return raw\n if (/^#[0-9a-f]{3}$/.test(raw)) return `#${raw[1]}${raw[1]}${raw[2]}${raw[2]}${raw[3]}${raw[3]}`\n return null\n}\n\n/**\n * A source's brand colors as it DRAWS them (AGL-4084): the colors its markup\n * and stylesheets use solid, most used first, the colorful before the greys.\n * A translucent color is a tint of one (a hover, a focus ring), never a use\n * of it, so it is not counted: aglyn.com's focus rings, a light blue at a\n * quarter strength, outnumbered the deep blue its buttons and links are\n * drawn in, which the theme reader would otherwise take as its brand.\n */\nexport function aiSiteImportBrandColors(page: Pick<AiReferencePage, 'html' | 'stylesheets'>): string[] {\n const weights = new Map<string, number>()\n const add = (hex: string | null, weight = 1) => {\n if (hex) weights.set(hex, (weights.get(hex) ?? 0) + weight)\n }\n for (const match of page.html.matchAll(THEME_COLOR)) add(hexOf(match[1] ?? ''), AI_THEME_THEME_COLOR_WEIGHT)\n for (const text of [page.html, ...page.stylesheets]) {\n for (const match of text.matchAll(SOLID_HEX)) add(hexOf(match[0]))\n for (const match of text.matchAll(SOLID_RGB)) {\n const alpha = match[4]\n if (alpha !== undefined && (alpha.endsWith('%') ? Number(alpha.slice(0, -1)) < 100 : Number(alpha) < 1)) continue\n const channels = [match[1], match[2], match[3]].map((value) => Math.min(255, Number(value)))\n add(`#${channels.map((value) => value.toString(16).padStart(2, '0')).join('')}`)\n }\n }\n return rankBrandColors(weights, AI_THEME_BRAND_COLORS_PER_SOURCE)\n}\n\n/** How colorful a color must be to carry a brand: the inspiration reader's own floor. */\nconst COLORFUL_CHROMA = 0.04\n\nconst colorful = (hex: string | null | undefined): hex is string => !!hex && /^#[0-9a-f]{6}$/i.test(hex) && aiHexOklch(hex).C >= COLORFUL_CHROMA\n\n/**\n * The brand and accent a source's look facts give (AGL-4108): the fill of\n * its filled buttons as the brand, the color of its links as the accent\n * where it is a color of its own, and the reverse where its buttons are not\n * colorful. The theme draws the brand at the nearest shade of it that reads\n * (`aiSiteColors`): aglyn.com's light blue buttons, under white words at\n * 2.4:1, come out at the deeper blue of its own links.\n */\nexport function aiSiteImportBrandOf(facts: (Pick<SiteImportLookFacts, 'buttonFill' | 'link'> & Pick<Partial<SiteImportLookFacts>, 'palette'>) | null | undefined): { brand: string; accent: string | null } | null {\n const fill = colorful(facts?.buttonFill) ? (facts?.buttonFill as string).toLowerCase() : null\n const link = colorful(facts?.link) ? (facts?.link as string).toLowerCase() : null\n // What its root declares its brand to be (AGL-4152), where nothing on its home page draws it.\n const palette = (facts?.palette ?? []).filter(colorful).map((hex) => hex.toLowerCase())\n const brand = fill ?? link ?? palette[0]\n if (!brand) return null\n return { brand, accent: (link && link !== brand ? link : palette.find((hex) => hex !== brand)) ?? null }\n}\n\nconst solidHex = (value: string | null | undefined): string | null => (value && /^#[0-9a-f]{6}$/i.test(value) ? value.toLowerCase() : null)\n\n/**\n * The look a source's signals pin (AGL-4084), drawn the way a guided start's\n * is: the kind of site its own description says, the import's seed, its\n * strongest color as the brand. What the reader found of its look\n * (`facts`, AGL-4108) pins it closer: its buttons' fill as the brand and its\n * links' color as the accent, its eyebrows' own color as the third, and its\n * own fonts where the catalog has them (`fonts`). Its pictures' colors\n * (`pictures`, AGL-4152) stand in for a brand where its facts show none. `null`\n * where nothing showed a color to carry a brand, unless asked to draw the look\n * from the seed alone (`draw`), which the pass does rather than leave the site\n * in the stock theme.\n *\n * How the owner asked the site to be finished (AGL-4152) says what else:\n * - **Keep my site** (`keep`, and an import that names none) pins the rest\n * of its look as it draws it: its page's ground and its dark bands', its\n * buttons' corners and case and their own fill and words, every inspiration\n * signal, and its eyebrows set as spaced capitals.\n * - **Improve it** (`improve`) pins only the brand, accent and third colors\n * and the fonts, so the base that suits the kind of site shows with its own\n * corners, buttons, grounds and eyebrows.\n */\nexport function aiSiteImportStyle(\n site: AiSiteInspirationSite | null,\n input: {\n seed: number\n description: string\n avoid?: readonly AiSiteStyle[]\n facts?: SiteImportLookFacts | null\n fonts?: AiSiteStyle['sourceFonts']\n finish?: AiSiteImportFinish | null\n pictures?: readonly string[]\n draw?: boolean\n },\n): AiSiteStyle | null {\n const facts = input.facts ?? null\n const finish: AiSiteImportFinish = input.finish === 'improve' ? 'improve' : 'keep'\n const pictured = input.pictures?.[0] ? { brand: input.pictures[0].toLowerCase(), accent: input.pictures[1]?.toLowerCase() ?? null } : null\n const own = aiSiteImportBrandOf(facts) ?? pictured\n if (!site && !own && !input.draw) return null\n const kind = aiSiteKindFor(input.description)\n const signals = site ? aiSiteInspirationLookPins({ v: 1, sites: [site], unread: 0 }, { kind, seed: input.seed }) : {}\n // Improve keeps the brand's colors and its type, and nothing else its source draws.\n const pins: AiSiteLookPins =\n finish === 'improve'\n ? {\n ...(signals.brand ? { brand: signals.brand } : {}),\n ...(signals.hue !== undefined ? { hue: signals.hue } : {}),\n ...(signals.accent !== undefined ? { accent: signals.accent } : {}),\n ...(signals.fonts ? { fonts: signals.fonts } : {}),\n }\n : signals\n if (own) {\n pins.brand = own.brand\n pins.hue = Math.round(aiHexOklch(own.brand).h) % 360\n if (own.accent) pins.accent = Math.round(aiHexOklch(own.accent).h) % 360\n }\n // Its buttons' corners round the theme's shape where its stylesheets did not say (AGL-4108).\n const radius = facts?.buttonRadius\n if (finish === 'keep' && typeof radius === 'number' && Number.isFinite(radius) && radius >= 0) {\n pins.buttons ??= radius >= 24 ? 'pill' : radius <= 2 ? 'square' : 'rounded'\n pins.corners ??= radius <= 2 ? 'sharp' : radius <= 10 ? 'soft' : radius <= 20 ? 'round' : 'pill'\n }\n // Its eyebrows as it sets them (AGL-4138): spaced capitals with no line before them — the\n // reader takes an eyebrow only in capitals, and no mark a page draws before one is a word of\n // it — and their own color, where it is one, as the theme's third.\n if (facts && finish === 'keep') pins.eyebrow = 'caps'\n if (colorful(facts?.eyebrow)) pins.tertiary = (facts?.eyebrow as string).toLowerCase()\n if (!pins.brand && !input.draw) return null\n const style = aiSiteStyleFor({ kind, answer: {}, seed: input.seed, brand: pins.brand, avoid: input.avoid ?? [], pins })\n const fonts = input.fonts ? { sourceFonts: input.fonts } : {}\n if (finish === 'improve') return { ...style, finish, ...fonts }\n // Keep my site (AGL-4152): its grounds, its buttons' case, and its filled buttons as it draws them.\n const page = solidHex(facts?.background)\n const darkPage = solidHex(facts?.darkBackground)\n const buttonFill = solidHex(facts?.buttonFill)\n const buttonText = buttonFill ? solidHex(facts?.buttonText) : null\n const caseOf = (value: string | null | undefined) => (value === 'upper' || value === 'none' ? value : null)\n const buttonCase = caseOf(facts?.buttonCase)\n const outlinedCase = caseOf(facts?.outlinedCase)\n const textCase = caseOf(facts?.textCase)\n const paper = solidHex(facts?.paperBackground)\n const darkPaper = solidHex(facts?.darkPaper)\n const outlinedFill = solidHex(facts?.outlinedFill)\n const buttonOutline = solidHex(facts?.buttonOutline)\n return {\n ...style,\n finish,\n ...(page ? { page } : {}),\n ...(darkPage ? { darkPage } : {}),\n ...(paper ? { paper } : {}),\n ...(darkPaper ? { darkPaper } : {}),\n ...(buttonCase ? { buttonCase } : {}),\n ...(outlinedCase ? { outlinedCase } : {}),\n ...(textCase ? { textCase } : {}),\n ...(outlinedFill ? { outlinedFill } : {}),\n ...(buttonOutline ? { buttonOutline } : {}),\n ...(buttonFill ? { buttonFill } : {}),\n ...(buttonText ? { buttonText } : {}),\n ...fonts,\n }\n}\n\n/** A family's facts, as the theme font catalog answers them. */\nexport type AiSiteImportFontFacts = (family: string) => Promise<ThemeFontFacts | undefined>\n\n/**\n * The source's own fonts (AGL-4108), each where the theme font catalog has\n * the family (Google Fonts', as the fonts plugin registers it), or the\n * source loads it from Google Fonts itself: its body's and its headings'.\n * `null` where its body's family is neither, and the pairing of the source's\n * type mood sets the site instead.\n */\nexport async function aiSiteImportSourceFonts(\n facts: Pick<SiteImportLookFacts, 'fonts'> | null | undefined,\n lookup: AiSiteImportFontFacts = themeFontFacts,\n): Promise<AiSiteStyle['sourceFonts']> {\n const fonts = facts?.fonts\n if (!fonts?.body) return null\n const loaded = new Set(fonts.google.map((family) => family.toLowerCase()))\n const resolve = async (family: string | null): Promise<AiSiteSourceFont | null> => {\n if (!family) return null\n const known = await lookup(family).catch(() => undefined)\n if (known) return { family: known.family, category: known.category, weights: [...known.weights] }\n return loaded.has(family.toLowerCase()) ? { family, category: 'sans-serif', weights: [] } : null\n }\n const body = await resolve(fonts.body)\n if (!body) return null\n const heading = fonts.headings && fonts.headings.toLowerCase() !== body.family.toLowerCase() ? await resolve(fonts.headings) : null\n return { body, heading }\n}\n\n/**\n * The site's listing in the home page's own words (AGL-4084), as field\n * paths: its title and description each only where the site still has the\n * one it was created with, so an owner's own listing is never written over.\n * `{}` with nothing to write.\n */\nexport function aiSiteImportListingUpdates(seo: unknown, displayName: unknown, home: Pick<AiSiteImportHome, 'title' | 'description'>): Record<string, string> {\n const seeded = aiSiteListingSeeded(seo, displayName)\n const current = (seo && typeof seo === 'object' ? seo : {}) as Record<string, unknown>\n const updates: Record<string, string> = {}\n const title = home.title.replace(/\\s+/g, ' ').trim()\n const description = home.description.replace(/\\s+/g, ' ').trim()\n if (title && seeded.title && title !== current['title']) updates['seo.title'] = title\n if (description && seeded.description && description !== current['description']) updates['seo.description'] = description\n return updates\n}\n\n/** Whether the site's share picture is still open: none, or the starter's (AGL-3988). */\nfunction shareOpen(seo: unknown): boolean {\n const image = (seo as { image?: unknown } | null | undefined)?.image\n if (image === undefined || image === null) return true\n return typeof image === 'string' && (!image.trim() || aiSiteIsStarterSrc(image))\n}\n\n/** Turns an SVG drawing into a PNG of a height; `null` where it cannot. */\nexport type AiSiteImportRasterize = (svg: Uint8Array, height: number) => Promise<Uint8Array | null>\n\nexport interface AiSiteImportLookDeps {\n fetch?: Fetch\n /** The edge headers for the source, asked with its domain; absent, the edge is asked as the crawl asks it (AGL-4108). */\n headersFor?: SiteImportCrawlSeams['headersFor']\n /** The edge's own answer, per address (`siteImportEdgeHeadersFor`), where no `headersFor` is given. */\n edgeHeadersFor?: typeof siteImportEdgeHeadersFor\n /** A family's facts in the theme font catalog (`themeFontFacts`). */\n fontFacts?: AiSiteImportFontFacts\n save?: typeof aiSaveSiteTheme\n others?: typeof aiWorkspaceSiteStyles\n ingest?: PluginMediaIngest | null\n rasterize?: AiSiteImportRasterize\n /** The site's document, as the listing reads it. */\n readHost?: (firestore: FirebaseFirestore.Firestore, hostId: string) => Promise<Record<string, unknown> | null>\n writeHost?: (firestore: FirebaseFirestore.Firestore, hostId: string, updates: Record<string, unknown>) => Promise<void>\n /** Re-fans the rows every site list reads a site's icon from (AGL-3972), after the look sets one. */\n syncMemberships?: (orgId: string, hostId: string) => Promise<void>\n /** A picture in the library's dominant colors (AGL-4152); `null` where it cannot be read. */\n pictureColors?: AiSiteImportPictureColors\n}\n\n/** A picture in the site's library's dominant colors (`dominantColorsFromPixels`). */\nexport type AiSiteImportPictureColors = (photo: AiSiteImportPhoto, input: { firestore: FirebaseFirestore.Firestore; hostId: string; orgId: string; signal?: AbortSignal }) => Promise<readonly string[] | null>\n\n/** The library's copy of a picture, decoded where `sharp` is shipped (`readLogoColors`, AGL-4048). */\nconst pictureColorsOf: AiSiteImportPictureColors = async (photo, { firestore, hostId, orgId, signal }) => {\n const location = logoMediaLocation(photo.src, hostId, orgId)\n if (!location) return null\n return readLogoColors(firestore, location, hostId, AbortSignal.any([AbortSignal.timeout(LOOK_READ_MS), ...(signal ? [signal] : [])]))\n}\n\n/** A read of a picture's colorful colors: none where it has none, or cannot be read. */\nasync function colorfulColorsOf(photo: AiSiteImportPhoto, read: AiSiteImportPictureColors, input: Parameters<AiSiteImportPictureColors>[1]): Promise<string[]> {\n const colors = await read(photo, input).catch((error: unknown) => {\n console.warn('[site-import] a picture’s colors could not be read', { hostId: input.hostId, error })\n return null\n })\n return (colors ?? []).filter(colorful).map((hex) => hex.toLowerCase())\n}\n\n/** The most pictures the home page's menus bring into the library (AGL-4139). */\nexport const AI_SITE_IMPORT_MENU_PICTURES = 4\n\n/** The pictures the home page's menus show (AGL-4139), each once, the first few: a featured card's. */\nexport function aiSiteImportMenuPictures(home: Pick<AiSiteImportHome, 'nav'>): Array<{ url: string; alt: string }> {\n const seen = new Set<string>()\n const out: Array<{ url: string; alt: string }> = []\n for (const group of home.nav?.items ?? []) {\n for (const column of group.columns ?? []) {\n if (!column.image || seen.has(column.image.url) || out.length >= AI_SITE_IMPORT_MENU_PICTURES) continue\n seen.add(column.image.url)\n out.push({ url: column.image.url, alt: column.image.alt })\n }\n }\n return out\n}\n\n/** Whether the site still has no icon of its own (AGL-4139): an owner's is never written over. */\nfunction faviconOpen(seo: unknown): boolean {\n const favicon = (seo as { favicon?: unknown } | null | undefined)?.favicon\n return favicon === undefined || favicon === null || (typeof favicon === 'string' && !favicon.trim())\n}\n\n\nexport interface AiSiteImportLookInput {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n orgId: string\n /** The member the logo and the share picture are stored as. */\n uid: string\n /** The import job's id, which the look's seed is drawn from. */\n jobId: string\n domain: string\n home: AiSiteImportHome\n at: string\n signal?: AbortSignal\n /** How the site is finished (AGL-4152): Keep my site keeps more of the source's look. Absent is `keep`. */\n finish?: AiSiteImportFinish | null\n}\n\nasync function readHostDoc(firestore: FirebaseFirestore.Firestore, hostId: string): Promise<Record<string, unknown> | null> {\n const snapshot = await firestore.collection('hosts').doc(hostId).get()\n return snapshot.exists ? ((snapshot.data() ?? {}) as Record<string, unknown>) : null\n}\n\nasync function writeHostDoc(firestore: FirebaseFirestore.Firestore, hostId: string, updates: Record<string, unknown>): Promise<void> {\n await firestore.collection('hosts').doc(hostId).update(updates)\n}\n\n/** Turns an SVG into a PNG in this process, where `sharp` is shipped; `null` where it is not. */\nasync function rasterizeHere(svg: Uint8Array, height: number): Promise<Uint8Array | null> {\n const images = await import('./ai-image-reads')\n const origin = images.aiImageReadsOrigin()\n if (origin) return images.requestAiLogoRaster(origin, svg, height)\n return images.rasterizeAiLogoSvg(svg, height)\n}\n\n/**\n * The source header's logo in the site's library (AGL-4084), once: the copy\n * a page already brought in is reused by its key. An SVG becomes a PNG.\n * `null` where it cannot be brought in, and the header then prints the name.\n */\nexport async function aiSiteImportLogo(\n input: { hostId: string; uid: string; domain: string; logo: NonNullable<AiSiteImportHome['brand']['logo']>; alt: string; headersFor?: SiteImportHeadersFor | null; signal?: AbortSignal },\n deps: { fetch?: Fetch; ingest: PluginMediaIngest | null; rasterize?: AiSiteImportRasterize },\n): Promise<AiSiteImportPhoto | null> {\n const ingest = deps.ingest\n const url = siteImportLogoUrl(input.logo.url)\n if (!ingest?.findImportedPhoto || !url) return null\n const sourceKey = siteImportImageKey(url)\n try {\n const held = await ingest.findImportedPhoto({ hostId: input.hostId, sourceKey })\n if (held) return { mediaId: held.mediaId, src: held.src, alt: input.alt, from: url, ...(held.width ? { width: held.width } : {}), ...(held.height ? { height: held.height } : {}) }\n const fetched = await (deps.fetch ?? fetchPublicTextDetailed)(url, {\n maxBytes: AI_SITE_IMPORT_LOGO_MAX_BYTES,\n accept: /^image\\//i,\n acceptHeader: 'image/svg+xml,image/png,image/webp,image/jpeg;q=0.9',\n userAgent: AGLYN_BOT_USER_AGENT,\n timeoutMs: LOOK_READ_MS,\n refuseOver: true,\n binary: true,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.headersFor ? { headersFor: input.headersFor } : {}),\n })\n if (!fetched.ok || !fetched.data?.byteLength) return null\n const type = fetched.contentType.split(';')[0].trim().toLowerCase()\n let bytes: Uint8Array | null = fetched.data\n let contentType = type\n if (type === 'image/svg+xml' || input.logo.type === 'svg') {\n bytes = await (deps.rasterize ?? rasterizeHere)(fetched.data, AI_SITE_IMPORT_LOGO_HEIGHT).catch(() => null)\n contentType = 'image/png'\n } else if (!/^image\\/(?:png|jpeg|webp|gif)$/.test(type)) {\n return null\n }\n if (!bytes?.byteLength) return null\n const stored = await ingest.ingest({\n hostId: input.hostId,\n uid: input.uid,\n fileName: `logo.${contentType === 'image/jpeg' ? 'jpg' : contentType.split('/')[1]}`,\n contentType,\n bytes,\n ...(input.alt ? { alt: input.alt.slice(0, 250) } : {}),\n importedFrom: { key: sourceKey, url, domain: input.domain },\n })\n if (!stored.ok) return null\n return { mediaId: stored.mediaId, src: stored.src, alt: input.alt, from: url, ...(stored.width ? { width: stored.width } : {}), ...(stored.height ? { height: stored.height } : {}) }\n } catch (error) {\n console.warn('[site-import] the logo could not be brought in', { hostId: input.hostId, error })\n return null\n }\n}\n\n/** The look pass (AGL-4084): the theme, the logo and the listing, from the owner's own home page. No model. */\nexport async function aiRunSiteImportLook(input: AiSiteImportLookInput, deps: AiSiteImportLookDeps = {}): Promise<AiSiteImportLook> {\n const { firestore, hostId, home } = input\n const headersFor = await aiSiteImportLookHeaders(input.domain, deps)\n const seed = aiSiteSeed(input.jobId)\n const page = await readSiteImportLookPage(home.url, { ...(deps.fetch ? { fetch: deps.fetch } : {}), headersFor, ...(input.signal ? { signal: input.signal } : {}) })\n // The source's own signals, its brand colors as it draws them solid.\n const signals = page ? aiSiteInspirationSignals(page) : null\n const site = signals && page ? { ...signals, colors: aiSiteImportBrandColors(page) } : signals\n const avoid = await (deps.others ?? aiWorkspaceSiteStyles)(firestore, { orgId: input.orgId, hostId })\n // What the reader found of its look, its buttons, ground and fonts (AGL-4108).\n const facts = home.look ?? null\n const fonts = await aiSiteImportSourceFonts(facts, deps.fontFacts)\n const ingest = deps.ingest ?? null\n const logo = home.brand.logo\n ? await aiSiteImportLogo(\n { hostId, uid: input.uid, domain: input.domain, logo: home.brand.logo, alt: home.siteName || home.brand.text, headersFor, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}), ...(deps.rasterize ? { rasterize: deps.rasterize } : {}) },\n )\n : null\n // No color of its own (AGL-4152): its logo's colorful colors, else its hero photo's, else its share picture's.\n let pictures: string[] = []\n let from: AiSiteImportLookFrom = 'source'\n if (!aiSiteImportBrandOf(facts)) {\n const read = deps.pictureColors ?? pictureColorsOf\n const asked = { firestore, hostId, orgId: input.orgId, ...(input.signal ? { signal: input.signal } : {}) }\n const ofLogo = logo ? await colorfulColorsOf(logo, read, asked) : []\n if (ofLogo.length) {\n pictures = ofLogo.slice(0, 2)\n from = 'logo'\n } else {\n for (const image of [home.hero, home.ogImage ? { url: home.ogImage, alt: '' } : null]) {\n if (!image) continue\n const { assets } = await bringInSiteImportPhotos(\n { hostId, uid: input.uid, domain: input.domain, images: [image], deadlineAt: Date.now() + LOOK_READ_MS, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}) },\n )\n const ofPhoto = assets[0] ? await colorfulColorsOf(assets[0], read, asked) : []\n if (!ofPhoto.length) continue\n pictures = ofPhoto.slice(0, 1)\n from = 'photo'\n break\n }\n }\n }\n const described = { seed, description: `${home.siteName} ${home.description}`, avoid, facts, fonts, finish: input.finish ?? null, pictures }\n let style = aiSiteImportStyle(site, described)\n // Nothing anywhere to read a color from: the seed's look for its kind, never the stock theme.\n if (!style) {\n style = aiSiteImportStyle(site, { ...described, draw: true }) as AiSiteStyle\n from = 'seed'\n }\n const saved = await (deps.save ?? aiSaveSiteTheme)(firestore, { hostId, jobId: input.jobId, style })\n if (saved.write === 'missing') throw new Error(`site ${hostId} vanished while its look was brought in`)\n const theme: AiSiteImportLook['theme'] = saved.write === 'kept' ? 'kept' : 'applied'\n // The pictures its menus show, in the library like its pages' photos (AGL-4139), for the header's panels.\n const menuImages = aiSiteImportMenuPictures(home)\n const menuPictures = menuImages.length\n ? (\n await bringInSiteImportPhotos(\n { hostId, uid: input.uid, domain: input.domain, images: menuImages, deadlineAt: Date.now() + LOOK_READ_MS, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}) },\n )\n ).assets\n : []\n // The site's listing in its own words, only over the one it was created with.\n let seo = false\n const host = await (deps.readHost ?? readHostDoc)(firestore, hostId)\n if (host) {\n const updates: Record<string, unknown> = aiSiteImportListingUpdates(host['seo'], host['displayName'], home)\n // The site's icon from the one its head names, where the site has none (AGL-4139).\n if (home.favicon && faviconOpen(host['seo'])) {\n const icon = await bringInSiteImportPhotos(\n { hostId, uid: input.uid, domain: input.domain, images: [{ url: home.favicon, alt: '' }], deadlineAt: Date.now() + LOOK_READ_MS, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}) },\n )\n const photo = icon.assets[0]\n if (photo) updates['seo.favicon'] = photo.src\n }\n if (home.ogImage && shareOpen(host['seo'])) {\n const share = await bringInSiteImportPhotos(\n { hostId, uid: input.uid, domain: input.domain, images: [{ url: home.ogImage, alt: '' }], deadlineAt: Date.now() + LOOK_READ_MS, ...(input.signal ? { signal: input.signal } : {}) },\n { ingest, ...(deps.fetch ? { fetch: deps.fetch } : {}) },\n )\n const photo = share.assets[0]\n if (photo) {\n updates['seo.image'] = photo.src\n if (photo.width) updates['seo.imageWidth'] = photo.width\n if (photo.height) updates['seo.imageHeight'] = photo.height\n }\n }\n if (Object.keys(updates).length) {\n await (deps.writeHost ?? writeHostDoc)(firestore, hostId, updates)\n seo = true\n // Every site list reads the icon the members' rows carry (AGL-3972).\n if (updates['seo.favicon']) {\n await (deps.syncMemberships ?? syncHostProjectionForMembers)(input.orgId, hostId).catch((error: unknown) => {\n console.warn('[site-import] the site lists were not told of the new icon', { hostId, error })\n })\n }\n }\n }\n const drawn = {\n ...(typeof style.headerAlign === 'string' ? { headerAlign: style.headerAlign } : {}),\n ...(typeof style.rhythm === 'string' ? { rhythm: style.rhythm } : {}),\n ...(typeof style.motion === 'string' ? { motion: style.motion } : {}),\n }\n const colors = [...new Set([...(facts ? [facts.buttonFill, facts.link, facts.eyebrow, ...(facts.palette ?? [])].filter(colorful).map((hex) => hex.toLowerCase()) : []), ...pictures, ...(site?.colors ?? [])])]\n return { at: input.at, theme, from, colors, logo, ...(menuPictures.length ? { pictures: menuPictures } : {}), seo, seed: style.seed, style: drawn }\n}\n\n/**\n * The headers the look's reads of the source go with, per address (AGL-4108),\n * exactly as the crawl's (`siteRequestHeaders`): the caller's where it hands\n * them in, else the edge's own, so a site this platform serves is read past\n * its challenge however the step was registered; and nothing for any address\n * off the site's two origins, a redirect hop's included. Never throws.\n *\n * The 10/29 look read went without the header twice over: no caller handed\n * one in, and the read passed headers the fetch does not take, which is why\n * this is a function the fetch asks for every hop (`headersFor`).\n */\nexport async function aiSiteImportLookHeaders(\n domain: string,\n deps: Pick<AiSiteImportLookDeps, 'headersFor' | 'edgeHeadersFor'>,\n): Promise<SiteImportHeadersFor> {\n const origins = siteImportOrigins(domain)\n let inner: SiteImportHeadersFor = NO_SITE_IMPORT_HEADERS\n try {\n if (deps.headersFor) {\n const headers = await deps.headersFor(domain)\n if (headers && Object.keys(headers).length) inner = () => headers\n } else {\n inner = await (deps.edgeHeadersFor ?? siteImportEdgeHeadersFor)(origins)\n }\n } catch (error) {\n console.warn('[site-import] the edge headers could not be read; reading the look without them', { domain, error })\n }\n return (url: URL) => (origins.includes(url.origin) ? inner(url) : {})\n}\n"],"names":["themeFontFacts","syncHostProjectionForMembers","aiSiteListingSeeded","aiSiteKindFor","aiHexOklch","aiSiteSeed","aiSiteStyleFor","aiSiteIsStarterSrc","AGLYN_BOT_USER_AGENT","siteImportOrigins","siteImportReadStylesheets","NO_SITE_IMPORT_HEADERS","siteImportEdgeHeadersFor","siteImportStylesheetLinks","bringInSiteImportPhotos","siteImportImageKey","siteImportLogoUrl","aiSaveSiteTheme","aiWorkspaceSiteStyles","aiSiteInspirationLookPins","aiSiteInspirationSignals","AI_THEME_BRAND_COLORS_PER_SOURCE","AI_THEME_REFERENCE_MAX_BYTES","AI_THEME_THEME_COLOR_WEIGHT","fetchPublicTextDetailed","logoMediaLocation","rankBrandColors","readLogoColors","AI_SITE_IMPORT_LOGO_HEIGHT","AI_SITE_IMPORT_LOGO_MAX_BYTES","LOOK_READ_MS","LOOK_SHEETS_MS","readSiteImportLookPage","url","input","fetchText","fetch","headersFor","read","address","maxBytes","accept","userAgent","timeoutMs","signal","catch","page","ok","startedAt","Date","now","stylesheets","text","sheet","outOfTime","html","SOLID_HEX","SOLID_RGB","THEME_COLOR","hexOf","value","raw","trim","toLowerCase","test","aiSiteImportBrandColors","match","weights","Map","add","hex","weight","set","get","matchAll","alpha","undefined","endsWith","Number","slice","channels","map","Math","min","toString","padStart","join","COLORFUL_CHROMA","colorful","C","aiSiteImportBrandOf","facts","fill","link","buttonFill","palette","filter","brand","accent","find","solidHex","aiSiteImportStyle","site","finish","pictured","pictures","own","draw","kind","description","signals","v","sites","unread","seed","pins","hue","fonts","round","h","radius","buttonRadius","isFinite","buttons","corners","eyebrow","tertiary","style","answer","avoid","sourceFonts","background","darkPage","darkBackground","buttonText","caseOf","buttonCase","outlinedCase","textCase","paper","paperBackground","darkPaper","outlinedFill","buttonOutline","aiSiteImportSourceFonts","lookup","body","loaded","Set","google","family","resolve","known","category","has","heading","headings","aiSiteImportListingUpdates","seo","displayName","home","seeded","current","updates","title","replace","shareOpen","image","pictureColorsOf","photo","firestore","hostId","orgId","location","src","AbortSignal","any","timeout","colorfulColorsOf","colors","error","console","warn","AI_SITE_IMPORT_MENU_PICTURES","aiSiteImportMenuPictures","seen","out","group","nav","items","column","columns","length","push","alt","faviconOpen","favicon","readHostDoc","snapshot","collection","doc","exists","data","writeHostDoc","update","rasterizeHere","svg","height","images","origin","aiImageReadsOrigin","requestAiLogoRaster","rasterizeAiLogoSvg","aiSiteImportLogo","deps","ingest","logo","findImportedPhoto","sourceKey","fetched","held","mediaId","from","width","acceptHeader","refuseOver","binary","byteLength","type","contentType","split","bytes","rasterize","stored","uid","fileName","importedFrom","key","domain","aiRunSiteImportLook","aiSiteImportLookHeaders","jobId","others","look","fontFacts","siteName","pictureColors","asked","ofLogo","hero","ogImage","assets","deadlineAt","ofPhoto","described","saved","save","write","Error","theme","menuImages","menuPictures","host","readHost","icon","share","Object","keys","writeHost","syncMemberships","drawn","headerAlign","rhythm","motion","at","origins","inner","headers","edgeHeadersFor","includes"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAuC2C;AAG3C,SAASA,cAAc,QAA6B,wDAAuD;AAC3G,SAASC,4BAA4B,QAAQ,mDAAkD;AAC/F,SAASC,mBAAmB,QAAQ,6BAAyB;AAE7D,SAASC,aAAa,QAAQ,4BAAwB;AACtD,SAASC,UAAU,EAAEC,UAAU,EAAEC,cAAc,QAAsE,2BAAuB;AAC5I,SAASC,kBAAkB,QAAQ,6BAAyB;AAC5D,SAASC,oBAAoB,EAAEC,iBAAiB,QAAmC,sCAAkC;AACrH,SAASC,yBAAyB,QAAQ,oCAAgC;AAC1E,SAASC,sBAAsB,EAAEC,wBAAwB,QAA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CAACU,SAASrF,MAAM,EAAEoF,QAAQ,IAAMC;QAC5D,OAAO;gBACU/D;YAAf8D,QAAQ,MAAM,EAAC9D,uBAAAA,KAAKgE,cAAc,YAAnBhE,uBAAuB1M,0BAA0BuQ;QAClE;IACF,EAAE,OAAO/F,OAAO;QACdC,QAAQC,IAAI,CAAC,mFAAmF;YAAEwD;YAAQ1D;QAAM;IAClH;IACA,OAAO,CAACnJ,MAAckP,QAAQI,QAAQ,CAACtP,IAAIgL,MAAM,IAAImE,MAAMnP,OAAO,CAAC;AACrE"}
@@ -82,6 +82,18 @@ export declare const logoMediaLocation: typeof aiMediaAssetLocation;
82
82
  * else is there.
83
83
  */
84
84
  export declare function dominantColorsFromPixels(data: ArrayLike<number>, channels: number, count?: number): string[];
85
+ /**
86
+ * A library logo's colors, read the way the media CDN would serve it
87
+ * (`readAiMediaAssetBytes`). `null` when the asset may not be read or the bytes
88
+ * cannot be decoded.
89
+ *
90
+ * On Vercel the read and the decode run in the plugins' image function, the
91
+ * one function that ships `sharp`'s native library (`ai-image-reads.ts`,
92
+ * AGL-4048), inside the brand reads' own bound (`signal`); anywhere else they
93
+ * run here. Either way an answer that does not come is a logo whose colors
94
+ * could not be read.
95
+ */
96
+ export declare function readLogoColors(firestore: FirebaseFirestore.Firestore, location: AiThemeLogoLocation, hostId: string, signal?: AbortSignal): Promise<string[] | null>;
85
97
  /**
86
98
  * A library logo's colors read and decoded in THIS process, from a location
87
99
  * already held to the media library's rule: what `readLogoColors` does off
@@ -140,7 +140,7 @@ const LOGO_TYPES = /^image\/(png|jpeg|webp|gif|avif|svg\+xml)$/;
140
140
  * AGL-4048), inside the brand reads' own bound (`signal`); anywhere else they
141
141
  * run here. Either way an answer that does not come is a logo whose colors
142
142
  * could not be read.
143
- */ async function readLogoColors(firestore, location, hostId, signal) {
143
+ */ export async function readLogoColors(firestore, location, hostId, signal) {
144
144
  const images = await import("./ai-image-reads.js");
145
145
  const origin = images.aiImageReadsOrigin();
146
146
  if (!origin) return readAiThemeLogoColorsAt(firestore, location, hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-theme-brand-inputs.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 { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type {\n AglynOrgBilling,\n OrgBrandingProfile,\n} from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { normalizeThemeHex } from '../tools/ai-theme-tool'\nimport { AI_THEME_BRAND_BUDGET_MS } from './ai-job-theme-budget'\nimport {\n aiMediaAssetLocation,\n loadAiMediaSharp,\n readAiMediaAssetBytes,\n type AiMediaAssetLocation,\n} from './ai-media-asset'\n\n/**\n * The brand a theme job builds on (AGL-2938): the colors that belong to the\n * site before anyone describes them.\n *\n * - **The workspace's brand color** — a white-label workspace's, and only\n * theirs: without the entitlement the resolved profile is the platform's,\n * which is no customer's brand.\n * - **The site logo** — when the logo is an asset of the site's own media\n * library or its org's, read from storage and reduced to its dominant\n * colors. Never fetched from a URL: a logo that is not a library asset is\n * left alone.\n * - **A page the brief links to** — fetched through the same SSRF guard the\n * plugin fetch proxy uses (a public address, pinned; https only; every\n * redirect re-validated), capped in bytes and time, and reduced to the\n * colors its markup and stylesheets use.\n *\n * Only hex colors leave this module. Nothing a page or a logo SAYS reaches a\n * prompt, so there is nothing in them to follow. Each source is best effort:\n * one that cannot be read is named in a note and the proposal is made\n * without it.\n */\n\nexport type AiThemeBrandSource = 'organization' | 'logo' | 'reference'\n\n/** How the prompt names where each brand color came from. */\nexport const AI_THEME_BRAND_SOURCE_WORDS: Record<AiThemeBrandSource, string> = {\n organization: 'the workspace brand color',\n logo: 'from the site logo',\n reference: 'from the page the brief links to',\n}\n\nexport interface AiThemeBrandColor {\n hex: string\n source: AiThemeBrandSource\n}\n\nexport interface AiThemeBrandInputs {\n colors: AiThemeBrandColor[]\n /** A source that could not be read, in customer-safe words. */\n notes: string[]\n}\n\n/** The most colors one source contributes. */\nexport const AI_THEME_BRAND_COLORS_PER_SOURCE = 4\n\n/** The largest logo decoded for its colors. */\nexport const AI_THEME_LOGO_MAX_BYTES = 5 * 1024 * 1024\n\n/** The most of a linked page, and of each of its stylesheets, that is read. */\nexport const AI_THEME_REFERENCE_MAX_BYTES = 512 * 1024\nexport const AI_THEME_STYLESHEET_MAX_BYTES = 256 * 1024\n\n/** The stylesheets of a linked page that are read beside it. */\nexport const AI_THEME_REFERENCE_STYLESHEETS = 2\n\n/**\n * The wall clock brand colors may take, declared with the theme step's time\n * (`ai-job-theme-budget.ts`), which counts it (AGL-3035).\n */\nexport { AI_THEME_BRAND_BUDGET_MS }\n\nconst FETCH_TIMEOUT_MS = 4_000\nconst MAX_REDIRECT_HOPS = 3\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\n\ntype Rgb = [red: number, green: number, blue: number]\n\nconst toHex = ([red, green, blue]: Rgb) =>\n `#${[red, green, blue]\n .map((channel) => Math.round(Math.min(255, Math.max(0, channel))).toString(16).padStart(2, '0'))\n .join('')}`\n\nconst channelsOf = (hex: string): Rgb => [\n parseInt(hex.slice(1, 3), 16),\n parseInt(hex.slice(3, 5), 16),\n parseInt(hex.slice(5, 7), 16),\n]\n\nconst distance = (a: Rgb, b: Rgb) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2])\n\n/** How far a color is from grey: the spread of its channels. */\nconst chroma = ([red, green, blue]: Rgb) => Math.max(red, green, blue) - Math.min(red, green, blue)\n\n/** Colors closer than this read as the same color in a palette. */\nconst SAME_COLOR_DISTANCE = 40\n\n/** A spread under this reads as a grey, which says little about a brand. */\nconst GREY_CHROMA = 38\n\n/** The distinct colors of a ranked list, colorful ones first when there are any. */\nfunction distinctColors(ranked: readonly Rgb[], count: number): string[] {\n const colorful = ranked.filter((color) => chroma(color) > GREY_CHROMA)\n const chosen: Rgb[] = []\n for (const color of colorful.length ? colorful : ranked) {\n if (chosen.some((other) => distance(other, color) < SAME_COLOR_DISTANCE)) continue\n chosen.push(color)\n if (chosen.length === count) break\n }\n return chosen.map(toHex)\n}\n\n/* ------------------------------------------------------------------------ *\n * The workspace's brand color\n * ------------------------------------------------------------------------ */\n\n/** A white-label workspace's own brand color; nothing for any other workspace. */\nexport function organizationBrandColors(\n org: Partial<AglynOrgBilling> | null | undefined,\n): AiThemeBrandColor[] {\n if (!checkEntitlement(org, 'whiteLabel')) return []\n const raw = (org?.brandingProfile as OrgBrandingProfile | undefined)?.primaryColor\n const hex = typeof raw === 'string' ? normalizeThemeHex(raw) : null\n return hex ? [{ hex, source: 'organization' }] : []\n}\n\n/* ------------------------------------------------------------------------ *\n * The site logo\n * ------------------------------------------------------------------------ */\n\nexport type AiThemeLogoLocation = AiMediaAssetLocation\n\n/**\n * Where a site's logo lives in a media library: a media reference or a CDN\n * path naming this site's library, or its org's. Anything else — an external\n * URL, an asset of some other site or org — has no location, and the logo is\n * left alone. The media library's own rule, shared with every job that reads\n * an asset (`ai-media-asset.ts`).\n */\nexport const logoMediaLocation = aiMediaAssetLocation\n\n/**\n * The dominant colors of an image's pixels: transparent pixels skipped, the\n * rest grouped into coarse buckets, the busiest distinct buckets first, and\n * the near-white and near-black edges a logo sits on dropped while anything\n * else is there.\n */\nexport function dominantColorsFromPixels(\n data: ArrayLike<number>,\n channels: number,\n count = AI_THEME_BRAND_COLORS_PER_SOURCE,\n): string[] {\n const buckets = new Map<number, { sum: Rgb; pixels: number }>()\n for (let index = 0; index + channels <= data.length; index += channels) {\n if (channels >= 4 && data[index + 3] < 128) continue\n const pixel: Rgb = [data[index], data[index + 1], data[index + 2]]\n const key = ((pixel[0] >> 4) << 8) | ((pixel[1] >> 4) << 4) | (pixel[2] >> 4)\n const bucket = buckets.get(key) ?? { sum: [0, 0, 0] as Rgb, pixels: 0 }\n bucket.sum = [bucket.sum[0] + pixel[0], bucket.sum[1] + pixel[1], bucket.sum[2] + pixel[2]]\n bucket.pixels += 1\n buckets.set(key, bucket)\n }\n const ranked = [...buckets.values()]\n .sort((a, b) => b.pixels - a.pixels)\n .map(({ sum, pixels }): Rgb => [sum[0] / pixels, sum[1] / pixels, sum[2] / pixels])\n const edge = (color: Rgb) => Math.min(...color) > 235 || Math.max(...color) < 20\n const inside = ranked.filter((color) => !edge(color))\n return distinctColors(inside.length ? inside : ranked, count)\n}\n\n/** The part of `sharp` the logo read uses. */\ninterface SharpPixelPipeline {\n resize(width: number, height: number, options: { fit: 'inside' }): SharpPixelPipeline\n ensureAlpha(): SharpPixelPipeline\n raw(): SharpPixelPipeline\n toBuffer(options: { resolveWithObject: true }): Promise<{\n data: Buffer\n info: { channels: number }\n }>\n}\ntype SharpPixels = (input: Buffer, options?: { limitInputPixels?: number }) => SharpPixelPipeline\n\nconst LOGO_TYPES = /^image\\/(png|jpeg|webp|gif|avif|svg\\+xml)$/\n\n/**\n * A library logo's colors, read the way the media CDN would serve it\n * (`readAiMediaAssetBytes`). `null` when the asset may not be read or the bytes\n * cannot be decoded.\n *\n * On Vercel the read and the decode run in the plugins' image function, the\n * one function that ships `sharp`'s native library (`ai-image-reads.ts`,\n * AGL-4048), inside the brand reads' own bound (`signal`); anywhere else they\n * run here. Either way an answer that does not come is a logo whose colors\n * could not be read.\n */\nasync function readLogoColors(\n firestore: FirebaseFirestore.Firestore,\n location: AiThemeLogoLocation,\n hostId: string,\n signal?: AbortSignal,\n): Promise<string[] | null> {\n const images = await import('./ai-image-reads')\n const origin = images.aiImageReadsOrigin()\n if (!origin) return readAiThemeLogoColorsAt(firestore, location, hostId)\n // The location was held to the site's org already: an org asset's scope\n // IS that org, and a site's own asset needs none.\n const orgId = location.scope.isOrg ? location.scope.scopeId : ''\n const payload = images.aiImageReadsRequest('logo-colors', location, hostId, orgId)\n if (!payload) return null\n const answer = await images.requestAiImageReads<{ colors?: unknown }>(\n origin,\n payload,\n signal ?? AbortSignal.timeout(AI_THEME_BRAND_BUDGET_MS),\n )\n return logoColorsAnswer(answer?.colors)\n}\n\n/**\n * A library logo's colors read and decoded in THIS process, from a location\n * already held to the media library's rule: what `readLogoColors` does off\n * Vercel, and what the images function does for it on Vercel.\n */\nexport async function readAiThemeLogoColorsAt(\n firestore: FirebaseFirestore.Firestore,\n location: AiThemeLogoLocation,\n hostId: string,\n): Promise<string[] | null> {\n const asset = await readAiMediaAssetBytes(firestore, location, hostId, {\n maxBytes: AI_THEME_LOGO_MAX_BYTES,\n types: LOGO_TYPES,\n })\n if (!asset) return null\n const sharp = (await loadAiMediaSharp()) as SharpPixels\n const { data, info } = await sharp(asset.buffer, { limitInputPixels: 64_000_000 })\n .resize(48, 48, { fit: 'inside' })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true })\n return dominantColorsFromPixels(data, info.channels)\n}\n\n/** What the images function answered, as hex colors: only colors leave it. */\nfunction logoColorsAnswer(colors: unknown): string[] | null {\n if (!Array.isArray(colors)) return null\n return colors\n .map((color) => (typeof color === 'string' ? normalizeThemeHex(color) : null))\n .filter((hex): hex is string => Boolean(hex))\n .slice(0, AI_THEME_BRAND_COLORS_PER_SOURCE)\n}\n\n/* ------------------------------------------------------------------------ *\n * A page the brief links to\n * ------------------------------------------------------------------------ */\n\nconst URL_IN_BRIEF = /\\bhttps?:\\/\\/[^\\s<>\"'`)\\]]+/i\n\n/** The first https link in a brief, or `null` — an http link is not followed. */\nexport function referenceUrlOf(brief: string): URL | null {\n const match = URL_IN_BRIEF.exec(brief)\n if (!match) return null\n try {\n const url = new URL(match[0].replace(/[.,;:!?]+$/, ''))\n return url.protocol === 'https:' ? url : null\n } catch {\n return null\n }\n}\n\n/** How much a page's declared `theme-color` counts beside one use of a color. */\nexport const AI_THEME_THEME_COLOR_WEIGHT = 25\n\nconst THEME_COLOR_META = /<meta\\b[^>]*\\bname\\s*=\\s*[\"']?theme-color\\b[^>]*>/gi\nconst CONTENT_ATTRIBUTE = /\\bcontent\\s*=\\s*[\"']?\\s*([^\"'\\s>]+)/i\n// A `#` after `&` is a character reference (`&#039;`), not a color.\nconst HEX_LITERAL = /(?<!&)#(?:[0-9a-f]{6}|[0-9a-f]{3})(?![0-9a-z])/gi\nconst RGB_LITERAL = /rgba?\\(\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})/gi\n\n/** Every color a page's markup or a stylesheet uses, weighted by how often. */\nexport function colorsFromMarkup(text: string): Map<string, number> {\n const weights = new Map<string, number>()\n const add = (hex: string | null, weight: number) => {\n if (hex) weights.set(hex, (weights.get(hex) ?? 0) + weight)\n }\n for (const tag of text.match(THEME_COLOR_META) ?? []) {\n add(normalizeThemeHex(CONTENT_ATTRIBUTE.exec(tag)?.[1] ?? ''), AI_THEME_THEME_COLOR_WEIGHT)\n }\n for (const match of text.matchAll(HEX_LITERAL)) add(normalizeThemeHex(match[0]), 1)\n for (const match of text.matchAll(RGB_LITERAL)) {\n add(toHex([Number(match[1]), Number(match[2]), Number(match[3])]), 1)\n }\n return weights\n}\n\nconst STYLESHEET_LINK = /<link\\b[^>]*\\brel\\s*=\\s*[\"']?stylesheet\\b[^>]*>/gi\nconst HREF_ATTRIBUTE = /\\bhref\\s*=\\s*[\"']?\\s*([^\"'\\s>]+)/i\n\n/** The https stylesheets a page links, resolved against it, at most a few. */\nexport function stylesheetUrlsOf(html: string, pageUrl: string): string[] {\n const urls: string[] = []\n for (const tag of html.match(STYLESHEET_LINK) ?? []) {\n const href = HREF_ATTRIBUTE.exec(tag)?.[1]\n if (!href) continue\n try {\n const url = new URL(href, pageUrl)\n if (url.protocol === 'https:' && !urls.includes(url.toString())) urls.push(url.toString())\n } catch {\n continue\n }\n if (urls.length === AI_THEME_REFERENCE_STYLESHEETS) break\n }\n return urls\n}\n\n/** The most used distinct colors, the colorful before the greys. */\nexport function rankBrandColors(\n weights: ReadonlyMap<string, number>,\n count = AI_THEME_BRAND_COLORS_PER_SOURCE,\n): string[] {\n const ranked = [...weights.entries()]\n .sort((a, b) => b[1] - a[1])\n .map(([hex]) => channelsOf(hex))\n return distinctColors(ranked, count)\n}\n\n/** One abort for the caller's signal and a clock, whichever ends first. */\nfunction deadline(signal: AbortSignal | undefined, ms: number) {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), ms)\n const onAbort = () => controller.abort()\n if (signal?.aborted) controller.abort()\n signal?.addEventListener('abort', onAbort)\n return {\n signal: controller.signal,\n done: () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n },\n }\n}\n\n/**\n * The body as text, to `maxBytes`. Past the cap it is cut there, or with\n * `refuseOver` it is not read at all: `null`, the read canceled.\n */\nasync function readCapped(\n body: ReadableStream<Uint8Array>,\n maxBytes: number,\n refuseOver = false,\n binary = false,\n): Promise<{ text: string; bytes: number; truncated: boolean; data?: Uint8Array } | null> {\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n let truncated = false\n for (;;) {\n const { done, value } = await reader.read()\n if (done || !value) break\n const room = maxBytes - total\n if (value.byteLength > room) {\n await reader.cancel().catch(() => undefined)\n if (refuseOver) return null\n chunks.push(value.subarray(0, room))\n total += room\n truncated = true\n break\n }\n chunks.push(value)\n total += value.byteLength\n }\n const joined = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n joined.set(chunk, offset)\n offset += chunk.byteLength\n }\n // A picture's bytes are kept as they came (AGL-3976), never decoded as text.\n if (binary) return { text: '', bytes: total, truncated, data: joined }\n return { text: new TextDecoder().decode(joined), bytes: total, truncated }\n}\n\n/** Why {@link fetchPublicTextDetailed} read nothing. */\nexport type PublicFetchRefusal =\n /** Not https, a port, credentials, or not a URL at all. */\n | 'refused-url'\n /** The name resolves to a private address, or not at all. */\n | 'private-address'\n /** A redirect the caller's `redirectAllowed` refused. */\n | 'redirect-refused'\n | 'too-many-redirects'\n /** An answer that was not 2xx; `status` says which. */\n | 'http-status'\n /** A 2xx whose content type the caller does not accept. */\n | 'content-type'\n /** Past `maxBytes` with `refuseOver` set. */\n | 'too-large'\n /** The socket, the clock or the caller's signal ended it. */\n | 'network'\n\n/**\n * One shape for both outcomes, read by `ok`: a union does not narrow across\n * this repo's library boundaries (`strictNullChecks` is off), so a caller\n * could not reach either arm's fields.\n */\nexport interface PublicFetchResult {\n ok: boolean\n /** The address read, after redirects; or the one that was refused. */\n url: string\n /** Empty unless `ok`. */\n text: string\n bytes: number\n /** Cut at `maxBytes` (never with `refuseOver`). */\n truncated: boolean\n contentType: string\n /** Null when `ok`. */\n refusal: PublicFetchRefusal | null\n status?: number\n /** Where a refused redirect pointed. */\n location?: string\n /** The body's bytes, with `binary`; absent otherwise. */\n data?: Uint8Array\n /**\n * Whose edge refused an error answer, when its headers say (AGL-4083): the\n * bot protection a site owner opens for AglynBot is that edge's setting.\n */\n edge?: PublicFetchEdge\n}\n\n/** An edge network that names itself on the answers it refuses with. */\nexport type PublicFetchEdge = 'vercel' | 'cloudflare'\n\n/** The edge an answer came through, from the headers each one sets; `null` for neither. */\nexport function publicFetchEdgeOf(headers: Pick<Headers, 'get'>): PublicFetchEdge | null {\n const server = (headers.get('server') ?? '').toLowerCase()\n if (headers.get('x-vercel-mitigated') || headers.get('x-vercel-id') || server === 'vercel') return 'vercel'\n if (headers.get('cf-mitigated') || headers.get('cf-ray') || server === 'cloudflare') return 'cloudflare'\n return null\n}\n\nfunction refusedFetch(\n refusal: PublicFetchRefusal,\n url: string,\n extra: { status?: number; location?: string; edge?: PublicFetchEdge } = {},\n): PublicFetchResult {\n return { ok: false, url, text: '', bytes: 0, truncated: false, contentType: '', refusal, ...extra }\n}\n\nexport interface PublicFetchOptions {\n maxBytes: number\n accept: RegExp\n signal?: AbortSignal\n timeoutMs?: number\n /** Sent as `User-Agent`; the runtime's own when absent. */\n userAgent?: string\n /** Sent as `Accept`. */\n acceptHeader?: string\n /**\n * More request headers for one hop, asked again for EVERY hop's own address\n * (AGL-4083, AGL-4085), so a header meant for one host never rides a\n * redirect to another. Sent under `Accept` and `User-Agent`, and neither\n * can be changed through here. The site import's edge header goes this\n * way, and only to the hosts `siteImportEdgeHeadersFor` decided are ours.\n */\n headersFor?: (url: URL) => Readonly<Record<string, string>> | undefined\n /** Asked of every redirect hop before it is followed; the SSRF checks run as well. */\n redirectAllowed?: (from: URL, to: URL) => boolean\n /** Refuse a body over `maxBytes` rather than cut it. */\n refuseOver?: boolean\n /** Keep the body's bytes as `data` rather than decode them as text (a picture, AGL-3976). */\n binary?: boolean\n}\n\n/** The caller's extra headers, without any that would say what the request is: those are the fetch's own. */\nfunction publicFetchExtraHeaders(headers: Readonly<Record<string, string>> | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers ?? {})) {\n if (/^(?:accept|user-agent|host|cookie|authorization|content-length)$/i.test(name)) continue\n if (typeof value === 'string') out[name] = value\n }\n return out\n}\n\n/**\n * A public https resource as text, through the plugin fetch proxy's SSRF\n * guard: the host must resolve only to public addresses and the socket is\n * pinned to the address checked; no credentials in the URL and no port but\n * the default; every redirect re-enters the same checks and the caller's own\n * `redirectAllowed`; the body is read to a byte cap under a clock, and only a\n * content type the caller accepts is read at all. Says why when it reads\n * nothing.\n */\nexport async function fetchPublicTextDetailed(\n url: string,\n options: PublicFetchOptions,\n): Promise<PublicFetchResult> {\n const { createPinnedDispatcher, resolvePublicIp } = await import('./ai-theme-brand-server')\n let current = url\n for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop += 1) {\n let parsed: URL\n try {\n parsed = new URL(current)\n } catch {\n return refusedFetch('refused-url', current)\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {\n return refusedFetch('refused-url', current)\n }\n if (parsed.port && parsed.port !== '443') {\n return refusedFetch('refused-url', current)\n }\n const pinned = await resolvePublicIp(parsed.hostname)\n if (!pinned) return refusedFetch('private-address', parsed.toString())\n const dispatcher = createPinnedDispatcher(pinned)\n const clock = deadline(options.signal, options.timeoutMs ?? FETCH_TIMEOUT_MS)\n try {\n // `dispatcher` is undici's, which the global fetch honors; a variable\n // rather than a literal keeps the DOM `RequestInit` check off it.\n const init = {\n method: 'GET',\n redirect: 'manual' as const,\n signal: clock.signal,\n dispatcher,\n headers: {\n ...publicFetchExtraHeaders(options.headersFor?.(parsed)),\n Accept: options.acceptHeader ?? 'text/html, text/css;q=0.9',\n ...(options.userAgent ? { 'User-Agent': options.userAgent } : {}),\n },\n }\n const response = await fetch(parsed.toString(), init as RequestInit)\n if (REDIRECT_STATUSES.has(response.status)) {\n await response.body?.cancel().catch(() => undefined)\n const location = response.headers.get('location')\n if (!location) {\n return refusedFetch('http-status', parsed.toString(), { status: response.status })\n }\n let next: URL\n try {\n next = new URL(location, parsed)\n } catch {\n return refusedFetch('redirect-refused', parsed.toString(), { location })\n }\n if (options.redirectAllowed && !options.redirectAllowed(parsed, next)) {\n return refusedFetch('redirect-refused', parsed.toString(), { location: next.toString() })\n }\n current = next.toString()\n continue\n }\n if (!response.ok || !response.body) {\n await response.body?.cancel().catch(() => undefined)\n const edge = publicFetchEdgeOf(response.headers)\n return refusedFetch('http-status', parsed.toString(), { status: response.status, ...(edge ? { edge } : {}) })\n }\n const contentType = response.headers.get('content-type') ?? ''\n if (!options.accept.test(contentType)) {\n await response.body.cancel().catch(() => undefined)\n return refusedFetch('content-type', parsed.toString(), { status: response.status })\n }\n const declared = Number(response.headers.get('content-length') ?? '')\n if (options.refuseOver && Number.isFinite(declared) && declared > options.maxBytes) {\n await response.body.cancel().catch(() => undefined)\n return refusedFetch('too-large', parsed.toString(), { status: response.status })\n }\n const body = await readCapped(response.body, options.maxBytes, options.refuseOver, options.binary === true)\n if (!body) {\n return refusedFetch('too-large', parsed.toString(), { status: response.status })\n }\n return { ok: true, url: parsed.toString(), contentType, refusal: null, ...body }\n } catch {\n return refusedFetch('network', parsed.toString())\n } finally {\n clock.done()\n await dispatcher.close().catch(() => undefined)\n }\n }\n return refusedFetch('too-many-redirects', current)\n}\n\n/** {@link fetchPublicTextDetailed}, answering `null` for anything it refused. */\nexport async function fetchPublicText(\n url: string,\n options: { maxBytes: number; accept: RegExp; signal?: AbortSignal; timeoutMs?: number; headersFor?: PublicFetchOptions['headersFor'] },\n): Promise<{ text: string; url: string } | null> {\n const result = await fetchPublicTextDetailed(url, options)\n return result.ok ? { text: result.text, url: result.url } : null\n}\n\n/**\n * A public page as it was read: its markup and the text of its first\n * stylesheets ({@link AI_THEME_REFERENCE_STYLESHEETS}), each under its byte\n * cap. What a theme job takes its colors from and a site start its\n * inspiration signals (AGL-3975); never a crawl, one page and its sheets.\n */\nexport interface AiReferencePage {\n /** The address the markup was finally read at, after redirects. */\n url: string\n html: string\n stylesheets: string[]\n}\n\n/**\n * A page and its first stylesheets through {@link fetchPublicText}; `null` when the page cannot be read.\n * `headersFor` is asked for every request and every redirect hop, the page's\n * and each stylesheet's, by its own address (AGL-4083, AGL-4085): the site\n * import's edge header, built by `siteImportEdgeHeadersFor`, answers only for\n * the site's own origins we serve, so a hop or a stylesheet anywhere else (a\n * CDN's, another site's) carries nothing.\n */\nexport async function readReferencePage(\n url: URL,\n signal: AbortSignal,\n headersFor?: PublicFetchOptions['headersFor'],\n): Promise<AiReferencePage | null> {\n const page = await fetchPublicText(url.toString(), {\n maxBytes: AI_THEME_REFERENCE_MAX_BYTES,\n accept: /text\\/html|application\\/xhtml\\+xml/i,\n signal,\n ...(headersFor ? { headersFor } : {}),\n })\n if (!page) return null\n const stylesheets: string[] = []\n for (const sheet of stylesheetUrlsOf(page.text, page.url)) {\n const css = await fetchPublicText(sheet, {\n maxBytes: AI_THEME_STYLESHEET_MAX_BYTES,\n accept: /text\\/css/i,\n signal,\n ...(headersFor ? { headersFor } : {}),\n })\n if (css) stylesheets.push(css.text)\n }\n return { url: page.url, html: page.text, stylesheets }\n}\n\n/** A read page's brand colors: every color its markup and stylesheets use, ranked. */\nexport function referencePageColors(page: Pick<AiReferencePage, 'html' | 'stylesheets'>): string[] {\n const weights = colorsFromMarkup(page.html)\n for (const css of page.stylesheets) {\n for (const [hex, weight] of colorsFromMarkup(css)) {\n weights.set(hex, (weights.get(hex) ?? 0) + weight)\n }\n }\n return rankBrandColors(weights)\n}\n\n/** A linked page's colors, from its markup and its first stylesheets. */\nasync function readReferenceColors(url: URL, signal: AbortSignal): Promise<string[] | null> {\n const page = await readReferencePage(url, signal)\n return page ? referencePageColors(page) : null\n}\n\n/* ------------------------------------------------------------------------ *\n * Gathering\n * ------------------------------------------------------------------------ */\n\n/** The two reads that leave the process, replaceable where a spec needs to. */\nexport interface AiThemeBrandSeams {\n logoColors?: (\n firestore: FirebaseFirestore.Firestore,\n location: AiThemeLogoLocation,\n hostId: string,\n /** The brand reads' bound, which a read made elsewhere waits no longer than. */\n signal?: AbortSignal,\n ) => Promise<string[] | null>\n referenceColors?: (url: URL, signal: AbortSignal) => Promise<string[] | null>\n}\n\nexport async function gatherAiThemeBrandInputs(\n input: {\n firestore: FirebaseFirestore.Firestore\n org: Partial<AglynOrgBilling> | null\n hostId: string\n /** The site's host document. */\n host: Record<string, unknown>\n brief: string\n signal?: AbortSignal\n },\n seams: AiThemeBrandSeams = {},\n): Promise<AiThemeBrandInputs> {\n const colors: AiThemeBrandColor[] = [...organizationBrandColors(input.org)]\n const notes: string[] = []\n const clock = deadline(input.signal, AI_THEME_BRAND_BUDGET_MS)\n const add = (found: readonly string[], source: AiThemeBrandSource) => {\n for (const hex of found.slice(0, AI_THEME_BRAND_COLORS_PER_SOURCE)) {\n if (!colors.some((color) => color.hex === hex)) colors.push({ hex, source })\n }\n }\n try {\n const location = logoMediaLocation(\n input.host['logoUrl'],\n input.hostId,\n String(input.host['orgId'] ?? ''),\n )\n if (location) {\n const found = await (seams.logoColors ?? readLogoColors)(\n input.firestore,\n location,\n input.hostId,\n clock.signal,\n ).catch(() => null)\n if (found) add(found, 'logo')\n else notes.push(\"The site logo's colors could not be read, so the proposal does not use them.\")\n }\n const reference = referenceUrlOf(input.brief)\n if (reference) {\n const found = clock.signal.aborted\n ? null\n : await (seams.referenceColors ?? readReferenceColors)(reference, clock.signal).catch(\n () => null,\n )\n if (found?.length) add(found, 'reference')\n else {\n notes.push(\n `The page at ${reference.hostname} could not be read for its colors, so the proposal does not use them.`,\n )\n }\n }\n } finally {\n clock.done()\n }\n return { colors, notes }\n}\n"],"names":["checkEntitlement","normalizeThemeHex","AI_THEME_BRAND_BUDGET_MS","aiMediaAssetLocation","loadAiMediaSharp","readAiMediaAssetBytes","AI_THEME_BRAND_SOURCE_WORDS","organization","logo","reference","AI_THEME_BRAND_COLORS_PER_SOURCE","AI_THEME_LOGO_MAX_BYTES","AI_THEME_REFERENCE_MAX_BYTES","AI_THEME_STYLESHEET_MAX_BYTES","AI_THEME_REFERENCE_STYLESHEETS","FETCH_TIMEOUT_MS","MAX_REDIRECT_HOPS","REDIRECT_STATUSES","Set","toHex","red","green","blue","map","channel","Math","round","min","max","toString","padStart","join","channelsOf","hex","parseInt","slice","distance","a","b","hypot","chroma","SAME_COLOR_DISTANCE","GREY_CHROMA","distinctColors","ranked","count","colorful","filter","color","chosen","length","some","other","push","organizationBrandColors","org","raw","brandingProfile","primaryColor","source","logoMediaLocation","dominantColorsFromPixels","data","channels","buckets","Map","index","pixel","key","bucket","get","sum","pixels","set","values","sort","edge","inside","LOGO_TYPES","readLogoColors","firestore","location","hostId","signal","images","origin","aiImageReadsOrigin","readAiThemeLogoColorsAt","orgId","scope","isOrg","scopeId","payload","aiImageReadsRequest","answer","requestAiImageReads","AbortSignal","timeout","logoColorsAnswer","colors","asset","maxBytes","types","sharp","info","buffer","limitInputPixels","resize","fit","ensureAlpha","toBuffer","resolveWithObject","Array","isArray","Boolean","URL_IN_BRIEF","referenceUrlOf","brief","match","exec","url","URL","replace","protocol","AI_THEME_THEME_COLOR_WEIGHT","THEME_COLOR_META","CONTENT_ATTRIBUTE","HEX_LITERAL","RGB_LITERAL","colorsFromMarkup","text","weights","add","weight","tag","matchAll","Number","STYLESHEET_LINK","HREF_ATTRIBUTE","stylesheetUrlsOf","html","pageUrl","urls","href","includes","rankBrandColors","entries","deadline","ms","controller","AbortController","timer","setTimeout","abort","onAbort","aborted","addEventListener","done","clearTimeout","removeEventListener","readCapped","body","refuseOver","binary","reader","getReader","chunks","total","truncated","value","read","room","byteLength","cancel","catch","undefined","subarray","joined","Uint8Array","offset","chunk","bytes","TextDecoder","decode","publicFetchEdgeOf","headers","server","toLowerCase","refusedFetch","refusal","extra","ok","contentType","publicFetchExtraHeaders","out","name","Object","test","fetchPublicTextDetailed","options","createPinnedDispatcher","resolvePublicIp","current","hop","parsed","username","password","port","pinned","hostname","dispatcher","clock","timeoutMs","response","init","method","redirect","headersFor","Accept","acceptHeader","userAgent","fetch","has","status","next","redirectAllowed","accept","declared","isFinite","close","fetchPublicText","result","readReferencePage","page","stylesheets","sheet","css","referencePageColors","readReferenceColors","gatherAiThemeBrandInputs","input","seams","notes","found","host","String","logoColors","referenceColors"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,2CAA0C;AAK3E,SAASC,iBAAiB,QAAQ,4BAAwB;AAC1D,SAASC,wBAAwB,QAAQ,2BAAuB;AAChE,SACEC,oBAAoB,EACpBC,gBAAgB,EAChBC,qBAAqB,QAEhB,sBAAkB;AA0BzB,2DAA2D,GAC3D,OAAO,MAAMC,8BAAkE;IAC7EC,cAAc;IACdC,MAAM;IACNC,WAAW;AACb,EAAC;AAaD,4CAA4C,GAC5C,OAAO,MAAMC,mCAAmC,EAAC;AAEjD,6CAA6C,GAC7C,OAAO,MAAMC,0BAA0B,IAAI,OAAO,KAAI;AAEtD,6EAA6E,GAC7E,OAAO,MAAMC,+BAA+B,MAAM,KAAI;AACtD,OAAO,MAAMC,gCAA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O;iBACjBD,MAAM7L,IAAI,CAAC;QAClB;QACA,MAAM5C,YAAY2G,eAAe4H,MAAM3H,KAAK;QAC5C,IAAI5G,WAAW;gBAGFwO;YAFX,MAAME,QAAQhC,MAAMhI,MAAM,CAACwE,OAAO,GAC9B,OACA,MAAM,EAACsF,yBAAAA,MAAMM,eAAe,YAArBN,yBAAyBH,qBAAqBrO,WAAW0M,MAAMhI,MAAM,EAAE2F,KAAK,CACjF,IAAM;YAEZ,IAAIqE,yBAAAA,MAAOjM,MAAM,EAAEkF,IAAI+G,OAAO;iBACzB;gBACHD,MAAM7L,IAAI,CACR,CAAC,YAAY,EAAE5C,UAAUwM,QAAQ,CAAC,qEAAqE,CAAC;YAE5G;QACF;IACF,SAAU;QACRE,MAAMtD,IAAI;IACZ;IACA,OAAO;QAAE1D;QAAQ+I;IAAM;AACzB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-theme-brand-inputs.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 { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type {\n AglynOrgBilling,\n OrgBrandingProfile,\n} from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { normalizeThemeHex } from '../tools/ai-theme-tool'\nimport { AI_THEME_BRAND_BUDGET_MS } from './ai-job-theme-budget'\nimport {\n aiMediaAssetLocation,\n loadAiMediaSharp,\n readAiMediaAssetBytes,\n type AiMediaAssetLocation,\n} from './ai-media-asset'\n\n/**\n * The brand a theme job builds on (AGL-2938): the colors that belong to the\n * site before anyone describes them.\n *\n * - **The workspace's brand color** — a white-label workspace's, and only\n * theirs: without the entitlement the resolved profile is the platform's,\n * which is no customer's brand.\n * - **The site logo** — when the logo is an asset of the site's own media\n * library or its org's, read from storage and reduced to its dominant\n * colors. Never fetched from a URL: a logo that is not a library asset is\n * left alone.\n * - **A page the brief links to** — fetched through the same SSRF guard the\n * plugin fetch proxy uses (a public address, pinned; https only; every\n * redirect re-validated), capped in bytes and time, and reduced to the\n * colors its markup and stylesheets use.\n *\n * Only hex colors leave this module. Nothing a page or a logo SAYS reaches a\n * prompt, so there is nothing in them to follow. Each source is best effort:\n * one that cannot be read is named in a note and the proposal is made\n * without it.\n */\n\nexport type AiThemeBrandSource = 'organization' | 'logo' | 'reference'\n\n/** How the prompt names where each brand color came from. */\nexport const AI_THEME_BRAND_SOURCE_WORDS: Record<AiThemeBrandSource, string> = {\n organization: 'the workspace brand color',\n logo: 'from the site logo',\n reference: 'from the page the brief links to',\n}\n\nexport interface AiThemeBrandColor {\n hex: string\n source: AiThemeBrandSource\n}\n\nexport interface AiThemeBrandInputs {\n colors: AiThemeBrandColor[]\n /** A source that could not be read, in customer-safe words. */\n notes: string[]\n}\n\n/** The most colors one source contributes. */\nexport const AI_THEME_BRAND_COLORS_PER_SOURCE = 4\n\n/** The largest logo decoded for its colors. */\nexport const AI_THEME_LOGO_MAX_BYTES = 5 * 1024 * 1024\n\n/** The most of a linked page, and of each of its stylesheets, that is read. */\nexport const AI_THEME_REFERENCE_MAX_BYTES = 512 * 1024\nexport const AI_THEME_STYLESHEET_MAX_BYTES = 256 * 1024\n\n/** The stylesheets of a linked page that are read beside it. */\nexport const AI_THEME_REFERENCE_STYLESHEETS = 2\n\n/**\n * The wall clock brand colors may take, declared with the theme step's time\n * (`ai-job-theme-budget.ts`), which counts it (AGL-3035).\n */\nexport { AI_THEME_BRAND_BUDGET_MS }\n\nconst FETCH_TIMEOUT_MS = 4_000\nconst MAX_REDIRECT_HOPS = 3\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\n\ntype Rgb = [red: number, green: number, blue: number]\n\nconst toHex = ([red, green, blue]: Rgb) =>\n `#${[red, green, blue]\n .map((channel) => Math.round(Math.min(255, Math.max(0, channel))).toString(16).padStart(2, '0'))\n .join('')}`\n\nconst channelsOf = (hex: string): Rgb => [\n parseInt(hex.slice(1, 3), 16),\n parseInt(hex.slice(3, 5), 16),\n parseInt(hex.slice(5, 7), 16),\n]\n\nconst distance = (a: Rgb, b: Rgb) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2])\n\n/** How far a color is from grey: the spread of its channels. */\nconst chroma = ([red, green, blue]: Rgb) => Math.max(red, green, blue) - Math.min(red, green, blue)\n\n/** Colors closer than this read as the same color in a palette. */\nconst SAME_COLOR_DISTANCE = 40\n\n/** A spread under this reads as a grey, which says little about a brand. */\nconst GREY_CHROMA = 38\n\n/** The distinct colors of a ranked list, colorful ones first when there are any. */\nfunction distinctColors(ranked: readonly Rgb[], count: number): string[] {\n const colorful = ranked.filter((color) => chroma(color) > GREY_CHROMA)\n const chosen: Rgb[] = []\n for (const color of colorful.length ? colorful : ranked) {\n if (chosen.some((other) => distance(other, color) < SAME_COLOR_DISTANCE)) continue\n chosen.push(color)\n if (chosen.length === count) break\n }\n return chosen.map(toHex)\n}\n\n/* ------------------------------------------------------------------------ *\n * The workspace's brand color\n * ------------------------------------------------------------------------ */\n\n/** A white-label workspace's own brand color; nothing for any other workspace. */\nexport function organizationBrandColors(\n org: Partial<AglynOrgBilling> | null | undefined,\n): AiThemeBrandColor[] {\n if (!checkEntitlement(org, 'whiteLabel')) return []\n const raw = (org?.brandingProfile as OrgBrandingProfile | undefined)?.primaryColor\n const hex = typeof raw === 'string' ? normalizeThemeHex(raw) : null\n return hex ? [{ hex, source: 'organization' }] : []\n}\n\n/* ------------------------------------------------------------------------ *\n * The site logo\n * ------------------------------------------------------------------------ */\n\nexport type AiThemeLogoLocation = AiMediaAssetLocation\n\n/**\n * Where a site's logo lives in a media library: a media reference or a CDN\n * path naming this site's library, or its org's. Anything else — an external\n * URL, an asset of some other site or org — has no location, and the logo is\n * left alone. The media library's own rule, shared with every job that reads\n * an asset (`ai-media-asset.ts`).\n */\nexport const logoMediaLocation = aiMediaAssetLocation\n\n/**\n * The dominant colors of an image's pixels: transparent pixels skipped, the\n * rest grouped into coarse buckets, the busiest distinct buckets first, and\n * the near-white and near-black edges a logo sits on dropped while anything\n * else is there.\n */\nexport function dominantColorsFromPixels(\n data: ArrayLike<number>,\n channels: number,\n count = AI_THEME_BRAND_COLORS_PER_SOURCE,\n): string[] {\n const buckets = new Map<number, { sum: Rgb; pixels: number }>()\n for (let index = 0; index + channels <= data.length; index += channels) {\n if (channels >= 4 && data[index + 3] < 128) continue\n const pixel: Rgb = [data[index], data[index + 1], data[index + 2]]\n const key = ((pixel[0] >> 4) << 8) | ((pixel[1] >> 4) << 4) | (pixel[2] >> 4)\n const bucket = buckets.get(key) ?? { sum: [0, 0, 0] as Rgb, pixels: 0 }\n bucket.sum = [bucket.sum[0] + pixel[0], bucket.sum[1] + pixel[1], bucket.sum[2] + pixel[2]]\n bucket.pixels += 1\n buckets.set(key, bucket)\n }\n const ranked = [...buckets.values()]\n .sort((a, b) => b.pixels - a.pixels)\n .map(({ sum, pixels }): Rgb => [sum[0] / pixels, sum[1] / pixels, sum[2] / pixels])\n const edge = (color: Rgb) => Math.min(...color) > 235 || Math.max(...color) < 20\n const inside = ranked.filter((color) => !edge(color))\n return distinctColors(inside.length ? inside : ranked, count)\n}\n\n/** The part of `sharp` the logo read uses. */\ninterface SharpPixelPipeline {\n resize(width: number, height: number, options: { fit: 'inside' }): SharpPixelPipeline\n ensureAlpha(): SharpPixelPipeline\n raw(): SharpPixelPipeline\n toBuffer(options: { resolveWithObject: true }): Promise<{\n data: Buffer\n info: { channels: number }\n }>\n}\ntype SharpPixels = (input: Buffer, options?: { limitInputPixels?: number }) => SharpPixelPipeline\n\nconst LOGO_TYPES = /^image\\/(png|jpeg|webp|gif|avif|svg\\+xml)$/\n\n/**\n * A library logo's colors, read the way the media CDN would serve it\n * (`readAiMediaAssetBytes`). `null` when the asset may not be read or the bytes\n * cannot be decoded.\n *\n * On Vercel the read and the decode run in the plugins' image function, the\n * one function that ships `sharp`'s native library (`ai-image-reads.ts`,\n * AGL-4048), inside the brand reads' own bound (`signal`); anywhere else they\n * run here. Either way an answer that does not come is a logo whose colors\n * could not be read.\n */\nexport async function readLogoColors(\n firestore: FirebaseFirestore.Firestore,\n location: AiThemeLogoLocation,\n hostId: string,\n signal?: AbortSignal,\n): Promise<string[] | null> {\n const images = await import('./ai-image-reads')\n const origin = images.aiImageReadsOrigin()\n if (!origin) return readAiThemeLogoColorsAt(firestore, location, hostId)\n // The location was held to the site's org already: an org asset's scope\n // IS that org, and a site's own asset needs none.\n const orgId = location.scope.isOrg ? location.scope.scopeId : ''\n const payload = images.aiImageReadsRequest('logo-colors', location, hostId, orgId)\n if (!payload) return null\n const answer = await images.requestAiImageReads<{ colors?: unknown }>(\n origin,\n payload,\n signal ?? AbortSignal.timeout(AI_THEME_BRAND_BUDGET_MS),\n )\n return logoColorsAnswer(answer?.colors)\n}\n\n/**\n * A library logo's colors read and decoded in THIS process, from a location\n * already held to the media library's rule: what `readLogoColors` does off\n * Vercel, and what the images function does for it on Vercel.\n */\nexport async function readAiThemeLogoColorsAt(\n firestore: FirebaseFirestore.Firestore,\n location: AiThemeLogoLocation,\n hostId: string,\n): Promise<string[] | null> {\n const asset = await readAiMediaAssetBytes(firestore, location, hostId, {\n maxBytes: AI_THEME_LOGO_MAX_BYTES,\n types: LOGO_TYPES,\n })\n if (!asset) return null\n const sharp = (await loadAiMediaSharp()) as SharpPixels\n const { data, info } = await sharp(asset.buffer, { limitInputPixels: 64_000_000 })\n .resize(48, 48, { fit: 'inside' })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true })\n return dominantColorsFromPixels(data, info.channels)\n}\n\n/** What the images function answered, as hex colors: only colors leave it. */\nfunction logoColorsAnswer(colors: unknown): string[] | null {\n if (!Array.isArray(colors)) return null\n return colors\n .map((color) => (typeof color === 'string' ? normalizeThemeHex(color) : null))\n .filter((hex): hex is string => Boolean(hex))\n .slice(0, AI_THEME_BRAND_COLORS_PER_SOURCE)\n}\n\n/* ------------------------------------------------------------------------ *\n * A page the brief links to\n * ------------------------------------------------------------------------ */\n\nconst URL_IN_BRIEF = /\\bhttps?:\\/\\/[^\\s<>\"'`)\\]]+/i\n\n/** The first https link in a brief, or `null` — an http link is not followed. */\nexport function referenceUrlOf(brief: string): URL | null {\n const match = URL_IN_BRIEF.exec(brief)\n if (!match) return null\n try {\n const url = new URL(match[0].replace(/[.,;:!?]+$/, ''))\n return url.protocol === 'https:' ? url : null\n } catch {\n return null\n }\n}\n\n/** How much a page's declared `theme-color` counts beside one use of a color. */\nexport const AI_THEME_THEME_COLOR_WEIGHT = 25\n\nconst THEME_COLOR_META = /<meta\\b[^>]*\\bname\\s*=\\s*[\"']?theme-color\\b[^>]*>/gi\nconst CONTENT_ATTRIBUTE = /\\bcontent\\s*=\\s*[\"']?\\s*([^\"'\\s>]+)/i\n// A `#` after `&` is a character reference (`&#039;`), not a color.\nconst HEX_LITERAL = /(?<!&)#(?:[0-9a-f]{6}|[0-9a-f]{3})(?![0-9a-z])/gi\nconst RGB_LITERAL = /rgba?\\(\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})\\s*[,\\s]\\s*(\\d{1,3})/gi\n\n/** Every color a page's markup or a stylesheet uses, weighted by how often. */\nexport function colorsFromMarkup(text: string): Map<string, number> {\n const weights = new Map<string, number>()\n const add = (hex: string | null, weight: number) => {\n if (hex) weights.set(hex, (weights.get(hex) ?? 0) + weight)\n }\n for (const tag of text.match(THEME_COLOR_META) ?? []) {\n add(normalizeThemeHex(CONTENT_ATTRIBUTE.exec(tag)?.[1] ?? ''), AI_THEME_THEME_COLOR_WEIGHT)\n }\n for (const match of text.matchAll(HEX_LITERAL)) add(normalizeThemeHex(match[0]), 1)\n for (const match of text.matchAll(RGB_LITERAL)) {\n add(toHex([Number(match[1]), Number(match[2]), Number(match[3])]), 1)\n }\n return weights\n}\n\nconst STYLESHEET_LINK = /<link\\b[^>]*\\brel\\s*=\\s*[\"']?stylesheet\\b[^>]*>/gi\nconst HREF_ATTRIBUTE = /\\bhref\\s*=\\s*[\"']?\\s*([^\"'\\s>]+)/i\n\n/** The https stylesheets a page links, resolved against it, at most a few. */\nexport function stylesheetUrlsOf(html: string, pageUrl: string): string[] {\n const urls: string[] = []\n for (const tag of html.match(STYLESHEET_LINK) ?? []) {\n const href = HREF_ATTRIBUTE.exec(tag)?.[1]\n if (!href) continue\n try {\n const url = new URL(href, pageUrl)\n if (url.protocol === 'https:' && !urls.includes(url.toString())) urls.push(url.toString())\n } catch {\n continue\n }\n if (urls.length === AI_THEME_REFERENCE_STYLESHEETS) break\n }\n return urls\n}\n\n/** The most used distinct colors, the colorful before the greys. */\nexport function rankBrandColors(\n weights: ReadonlyMap<string, number>,\n count = AI_THEME_BRAND_COLORS_PER_SOURCE,\n): string[] {\n const ranked = [...weights.entries()]\n .sort((a, b) => b[1] - a[1])\n .map(([hex]) => channelsOf(hex))\n return distinctColors(ranked, count)\n}\n\n/** One abort for the caller's signal and a clock, whichever ends first. */\nfunction deadline(signal: AbortSignal | undefined, ms: number) {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), ms)\n const onAbort = () => controller.abort()\n if (signal?.aborted) controller.abort()\n signal?.addEventListener('abort', onAbort)\n return {\n signal: controller.signal,\n done: () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n },\n }\n}\n\n/**\n * The body as text, to `maxBytes`. Past the cap it is cut there, or with\n * `refuseOver` it is not read at all: `null`, the read canceled.\n */\nasync function readCapped(\n body: ReadableStream<Uint8Array>,\n maxBytes: number,\n refuseOver = false,\n binary = false,\n): Promise<{ text: string; bytes: number; truncated: boolean; data?: Uint8Array } | null> {\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n let truncated = false\n for (;;) {\n const { done, value } = await reader.read()\n if (done || !value) break\n const room = maxBytes - total\n if (value.byteLength > room) {\n await reader.cancel().catch(() => undefined)\n if (refuseOver) return null\n chunks.push(value.subarray(0, room))\n total += room\n truncated = true\n break\n }\n chunks.push(value)\n total += value.byteLength\n }\n const joined = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n joined.set(chunk, offset)\n offset += chunk.byteLength\n }\n // A picture's bytes are kept as they came (AGL-3976), never decoded as text.\n if (binary) return { text: '', bytes: total, truncated, data: joined }\n return { text: new TextDecoder().decode(joined), bytes: total, truncated }\n}\n\n/** Why {@link fetchPublicTextDetailed} read nothing. */\nexport type PublicFetchRefusal =\n /** Not https, a port, credentials, or not a URL at all. */\n | 'refused-url'\n /** The name resolves to a private address, or not at all. */\n | 'private-address'\n /** A redirect the caller's `redirectAllowed` refused. */\n | 'redirect-refused'\n | 'too-many-redirects'\n /** An answer that was not 2xx; `status` says which. */\n | 'http-status'\n /** A 2xx whose content type the caller does not accept. */\n | 'content-type'\n /** Past `maxBytes` with `refuseOver` set. */\n | 'too-large'\n /** The socket, the clock or the caller's signal ended it. */\n | 'network'\n\n/**\n * One shape for both outcomes, read by `ok`: a union does not narrow across\n * this repo's library boundaries (`strictNullChecks` is off), so a caller\n * could not reach either arm's fields.\n */\nexport interface PublicFetchResult {\n ok: boolean\n /** The address read, after redirects; or the one that was refused. */\n url: string\n /** Empty unless `ok`. */\n text: string\n bytes: number\n /** Cut at `maxBytes` (never with `refuseOver`). */\n truncated: boolean\n contentType: string\n /** Null when `ok`. */\n refusal: PublicFetchRefusal | null\n status?: number\n /** Where a refused redirect pointed. */\n location?: string\n /** The body's bytes, with `binary`; absent otherwise. */\n data?: Uint8Array\n /**\n * Whose edge refused an error answer, when its headers say (AGL-4083): the\n * bot protection a site owner opens for AglynBot is that edge's setting.\n */\n edge?: PublicFetchEdge\n}\n\n/** An edge network that names itself on the answers it refuses with. */\nexport type PublicFetchEdge = 'vercel' | 'cloudflare'\n\n/** The edge an answer came through, from the headers each one sets; `null` for neither. */\nexport function publicFetchEdgeOf(headers: Pick<Headers, 'get'>): PublicFetchEdge | null {\n const server = (headers.get('server') ?? '').toLowerCase()\n if (headers.get('x-vercel-mitigated') || headers.get('x-vercel-id') || server === 'vercel') return 'vercel'\n if (headers.get('cf-mitigated') || headers.get('cf-ray') || server === 'cloudflare') return 'cloudflare'\n return null\n}\n\nfunction refusedFetch(\n refusal: PublicFetchRefusal,\n url: string,\n extra: { status?: number; location?: string; edge?: PublicFetchEdge } = {},\n): PublicFetchResult {\n return { ok: false, url, text: '', bytes: 0, truncated: false, contentType: '', refusal, ...extra }\n}\n\nexport interface PublicFetchOptions {\n maxBytes: number\n accept: RegExp\n signal?: AbortSignal\n timeoutMs?: number\n /** Sent as `User-Agent`; the runtime's own when absent. */\n userAgent?: string\n /** Sent as `Accept`. */\n acceptHeader?: string\n /**\n * More request headers for one hop, asked again for EVERY hop's own address\n * (AGL-4083, AGL-4085), so a header meant for one host never rides a\n * redirect to another. Sent under `Accept` and `User-Agent`, and neither\n * can be changed through here. The site import's edge header goes this\n * way, and only to the hosts `siteImportEdgeHeadersFor` decided are ours.\n */\n headersFor?: (url: URL) => Readonly<Record<string, string>> | undefined\n /** Asked of every redirect hop before it is followed; the SSRF checks run as well. */\n redirectAllowed?: (from: URL, to: URL) => boolean\n /** Refuse a body over `maxBytes` rather than cut it. */\n refuseOver?: boolean\n /** Keep the body's bytes as `data` rather than decode them as text (a picture, AGL-3976). */\n binary?: boolean\n}\n\n/** The caller's extra headers, without any that would say what the request is: those are the fetch's own. */\nfunction publicFetchExtraHeaders(headers: Readonly<Record<string, string>> | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers ?? {})) {\n if (/^(?:accept|user-agent|host|cookie|authorization|content-length)$/i.test(name)) continue\n if (typeof value === 'string') out[name] = value\n }\n return out\n}\n\n/**\n * A public https resource as text, through the plugin fetch proxy's SSRF\n * guard: the host must resolve only to public addresses and the socket is\n * pinned to the address checked; no credentials in the URL and no port but\n * the default; every redirect re-enters the same checks and the caller's own\n * `redirectAllowed`; the body is read to a byte cap under a clock, and only a\n * content type the caller accepts is read at all. Says why when it reads\n * nothing.\n */\nexport async function fetchPublicTextDetailed(\n url: string,\n options: PublicFetchOptions,\n): Promise<PublicFetchResult> {\n const { createPinnedDispatcher, resolvePublicIp } = await import('./ai-theme-brand-server')\n let current = url\n for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop += 1) {\n let parsed: URL\n try {\n parsed = new URL(current)\n } catch {\n return refusedFetch('refused-url', current)\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {\n return refusedFetch('refused-url', current)\n }\n if (parsed.port && parsed.port !== '443') {\n return refusedFetch('refused-url', current)\n }\n const pinned = await resolvePublicIp(parsed.hostname)\n if (!pinned) return refusedFetch('private-address', parsed.toString())\n const dispatcher = createPinnedDispatcher(pinned)\n const clock = deadline(options.signal, options.timeoutMs ?? FETCH_TIMEOUT_MS)\n try {\n // `dispatcher` is undici's, which the global fetch honors; a variable\n // rather than a literal keeps the DOM `RequestInit` check off it.\n const init = {\n method: 'GET',\n redirect: 'manual' as const,\n signal: clock.signal,\n dispatcher,\n headers: {\n ...publicFetchExtraHeaders(options.headersFor?.(parsed)),\n Accept: options.acceptHeader ?? 'text/html, text/css;q=0.9',\n ...(options.userAgent ? { 'User-Agent': options.userAgent } : {}),\n },\n }\n const response = await fetch(parsed.toString(), init as RequestInit)\n if (REDIRECT_STATUSES.has(response.status)) {\n await response.body?.cancel().catch(() => undefined)\n const location = response.headers.get('location')\n if (!location) {\n return refusedFetch('http-status', parsed.toString(), { status: response.status })\n }\n let next: URL\n try {\n next = new URL(location, parsed)\n } catch {\n return refusedFetch('redirect-refused', parsed.toString(), { location })\n }\n if (options.redirectAllowed && !options.redirectAllowed(parsed, next)) {\n return refusedFetch('redirect-refused', parsed.toString(), { location: next.toString() })\n }\n current = next.toString()\n continue\n }\n if (!response.ok || !response.body) {\n await response.body?.cancel().catch(() => undefined)\n const edge = publicFetchEdgeOf(response.headers)\n return refusedFetch('http-status', parsed.toString(), { status: response.status, ...(edge ? { edge } : {}) })\n }\n const contentType = response.headers.get('content-type') ?? ''\n if (!options.accept.test(contentType)) {\n await response.body.cancel().catch(() => undefined)\n return refusedFetch('content-type', parsed.toString(), { status: response.status })\n }\n const declared = Number(response.headers.get('content-length') ?? '')\n if (options.refuseOver && Number.isFinite(declared) && declared > options.maxBytes) {\n await response.body.cancel().catch(() => undefined)\n return refusedFetch('too-large', parsed.toString(), { status: response.status })\n }\n const body = await readCapped(response.body, options.maxBytes, options.refuseOver, options.binary === true)\n if (!body) {\n return refusedFetch('too-large', parsed.toString(), { status: response.status })\n }\n return { ok: true, url: parsed.toString(), contentType, refusal: null, ...body }\n } catch {\n return refusedFetch('network', parsed.toString())\n } finally {\n clock.done()\n await dispatcher.close().catch(() => undefined)\n }\n }\n return refusedFetch('too-many-redirects', current)\n}\n\n/** {@link fetchPublicTextDetailed}, answering `null` for anything it refused. */\nexport async function fetchPublicText(\n url: string,\n options: { maxBytes: number; accept: RegExp; signal?: AbortSignal; timeoutMs?: number; headersFor?: PublicFetchOptions['headersFor'] },\n): Promise<{ text: string; url: string } | null> {\n const result = await fetchPublicTextDetailed(url, options)\n return result.ok ? { text: result.text, url: result.url } : null\n}\n\n/**\n * A public page as it was read: its markup and the text of its first\n * stylesheets ({@link AI_THEME_REFERENCE_STYLESHEETS}), each under its byte\n * cap. What a theme job takes its colors from and a site start its\n * inspiration signals (AGL-3975); never a crawl, one page and its sheets.\n */\nexport interface AiReferencePage {\n /** The address the markup was finally read at, after redirects. */\n url: string\n html: string\n stylesheets: string[]\n}\n\n/**\n * A page and its first stylesheets through {@link fetchPublicText}; `null` when the page cannot be read.\n * `headersFor` is asked for every request and every redirect hop, the page's\n * and each stylesheet's, by its own address (AGL-4083, AGL-4085): the site\n * import's edge header, built by `siteImportEdgeHeadersFor`, answers only for\n * the site's own origins we serve, so a hop or a stylesheet anywhere else (a\n * CDN's, another site's) carries nothing.\n */\nexport async function readReferencePage(\n url: URL,\n signal: AbortSignal,\n headersFor?: PublicFetchOptions['headersFor'],\n): Promise<AiReferencePage | null> {\n const page = await fetchPublicText(url.toString(), {\n maxBytes: AI_THEME_REFERENCE_MAX_BYTES,\n accept: /text\\/html|application\\/xhtml\\+xml/i,\n signal,\n ...(headersFor ? { headersFor } : {}),\n })\n if (!page) return null\n const stylesheets: string[] = []\n for (const sheet of stylesheetUrlsOf(page.text, page.url)) {\n const css = await fetchPublicText(sheet, {\n maxBytes: AI_THEME_STYLESHEET_MAX_BYTES,\n accept: /text\\/css/i,\n signal,\n ...(headersFor ? { headersFor } : {}),\n })\n if (css) stylesheets.push(css.text)\n }\n return { url: page.url, html: page.text, stylesheets }\n}\n\n/** A read page's brand colors: every color its markup and stylesheets use, ranked. */\nexport function referencePageColors(page: Pick<AiReferencePage, 'html' | 'stylesheets'>): string[] {\n const weights = colorsFromMarkup(page.html)\n for (const css of page.stylesheets) {\n for (const [hex, weight] of colorsFromMarkup(css)) {\n weights.set(hex, (weights.get(hex) ?? 0) + weight)\n }\n }\n return rankBrandColors(weights)\n}\n\n/** A linked page's colors, from its markup and its first stylesheets. */\nasync function readReferenceColors(url: URL, signal: AbortSignal): Promise<string[] | null> {\n const page = await readReferencePage(url, signal)\n return page ? referencePageColors(page) : null\n}\n\n/* ------------------------------------------------------------------------ *\n * Gathering\n * ------------------------------------------------------------------------ */\n\n/** The two reads that leave the process, replaceable where a spec needs to. */\nexport interface AiThemeBrandSeams {\n logoColors?: (\n firestore: FirebaseFirestore.Firestore,\n location: AiThemeLogoLocation,\n hostId: string,\n /** The brand reads' bound, which a read made elsewhere waits no longer than. */\n signal?: AbortSignal,\n ) => Promise<string[] | null>\n referenceColors?: (url: URL, signal: AbortSignal) => Promise<string[] | null>\n}\n\nexport async function gatherAiThemeBrandInputs(\n input: {\n firestore: FirebaseFirestore.Firestore\n org: Partial<AglynOrgBilling> | null\n hostId: string\n /** The site's host document. */\n host: Record<string, unknown>\n brief: string\n signal?: AbortSignal\n },\n seams: AiThemeBrandSeams = {},\n): Promise<AiThemeBrandInputs> {\n const colors: AiThemeBrandColor[] = [...organizationBrandColors(input.org)]\n const notes: string[] = []\n const clock = deadline(input.signal, AI_THEME_BRAND_BUDGET_MS)\n const add = (found: readonly string[], source: AiThemeBrandSource) => {\n for (const hex of found.slice(0, AI_THEME_BRAND_COLORS_PER_SOURCE)) {\n if (!colors.some((color) => color.hex === hex)) colors.push({ hex, source })\n }\n }\n try {\n const location = logoMediaLocation(\n input.host['logoUrl'],\n input.hostId,\n String(input.host['orgId'] ?? ''),\n )\n if (location) {\n const found = await (seams.logoColors ?? readLogoColors)(\n input.firestore,\n location,\n input.hostId,\n clock.signal,\n ).catch(() => null)\n if (found) add(found, 'logo')\n else notes.push(\"The site logo's colors could not be read, so the proposal does not use them.\")\n }\n const reference = referenceUrlOf(input.brief)\n if (reference) {\n const found = clock.signal.aborted\n ? null\n : await (seams.referenceColors ?? readReferenceColors)(reference, clock.signal).catch(\n () => null,\n )\n if (found?.length) add(found, 'reference')\n else {\n notes.push(\n `The page at ${reference.hostname} could not be read for its colors, so the proposal does not use them.`,\n )\n }\n }\n } finally {\n clock.done()\n }\n return { colors, notes }\n}\n"],"names":["checkEntitlement","normalizeThemeHex","AI_THEME_BRAND_BUDGET_MS","aiMediaAssetLocation","loadAiMediaSharp","readAiMediaAssetBytes","AI_THEME_BRAND_SOURCE_WORDS","organization","logo","reference","AI_THEME_BRAND_COLORS_PER_SOURCE","AI_THEME_LOGO_MAX_BYTES","AI_THEME_REFERENCE_MAX_BYTES","AI_THEME_STYLESHEET_MAX_BYTES","AI_THEME_REFERENCE_STYLESHEETS","FETCH_TIMEOUT_MS","MAX_REDIRECT_HOPS","REDIRECT_STATUSES","Set","toHex","red","green","blue","map","channel","Math","round","min","max","toString","padStart","join","channelsOf","hex","parseInt","slice","distance","a","b","hypot","chroma","SAME_COLOR_DISTANCE","GREY_CHROMA","distinctColors","ranked","count","colorful","filter","color","chosen","length","some","other","push","organizationBrandColors","org","raw","brandingProfile","primaryColor","source","logoMediaLocation","dominantColorsFromPixels","data","channels","buckets","Map","index","pixel","key","bucket","get","sum","pixels","set","values","sort","edge","inside","LOGO_TYPES","readLogoColors","firestore","location","hostId","signal","images","origin","aiImageReadsOrigin","readAiThemeLogoColorsAt","orgId","scope","isOrg","scopeId","payload","aiImageReadsRequest","answer","requestAiImageReads","AbortSignal","timeout","logoColorsAnswer","colors","asset","maxBytes","types","sharp","info","buffer","limitInputPixels","resize","fit","ensureAlpha","toBuffer","resolveWithObject","Array","isArray","Boolean","URL_IN_BRIEF","referenceUrlOf","brief","match","exec","url","URL","replace","protocol","AI_THEME_THEME_COLOR_WEIGHT","THEME_COLOR_META","CONTENT_ATTRIBUTE","HEX_LITERAL","RGB_LITERAL","colorsFromMarkup","text","weights","add","weight","tag","matchAll","Number","STYLESHEET_LINK","HREF_ATTRIBUTE","stylesheetUrlsOf","html","pageUrl","urls","href","includes","rankBrandColors","entries","deadline","ms","controller","AbortController","timer","setTimeout","abort","onAbort","aborted","addEventListener","done","clearTimeout","removeEventListener","readCapped","body","refuseOver","binary","reader","getReader","chunks","total","truncated","value","read","room","byteLength","cancel","catch","undefined","subarray","joined","Uint8Array","offset","chunk","bytes","TextDecoder","decode","publicFetchEdgeOf","headers","server","toLowerCase","refusedFetch","refusal","extra","ok","contentType","publicFetchExtraHeaders","out","name","Object","test","fetchPublicTextDetailed","options","createPinnedDispatcher","resolvePublicIp","current","hop","parsed","username","password","port","pinned","hostname","dispatcher","clock","timeoutMs","response","init","method","redirect","headersFor","Accept","acceptHeader","userAgent","fetch","has","status","next","redirectAllowed","accept","declared","isFinite","close","fetchPublicText","result","readReferencePage","page","stylesheets","sheet","css","referencePageColors","readReferenceColors","gatherAiThemeBrandInputs","input","seams","notes","found","host","String","logoColors","referenceColors"],"mappings":";AAAA;;;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UA,MAAMf,GAAG,KAAKA,MAAMkE,OAAO9C,IAAI,CAAC;gBAAEpB;gBAAK0B;YAAO;QAC5E;IACF;IACA,IAAI;YAIOqL;QAHT,MAAM/J,WAAWrB,kBACfoL,MAAMI,IAAI,CAAC,UAAU,EACrBJ,MAAM9J,MAAM,EACZmK,QAAOL,oBAAAA,MAAMI,IAAI,CAAC,QAAQ,YAAnBJ,oBAAuB;QAEhC,IAAI/J,UAAU;gBACSgK;YAArB,MAAME,QAAQ,MAAM,EAACF,oBAAAA,MAAMK,UAAU,YAAhBL,oBAAoBlK,gBACvCiK,MAAMhK,SAAS,EACfC,UACA+J,MAAM9J,MAAM,EACZiI,MAAMhI,MAAM,EACZ2F,KAAK,CAAC,IAAM;YACd,IAAIqE,OAAO/G,IAAI+G,OAAO;iBACjBD,MAAM7L,IAAI,CAAC;QAClB;QACA,MAAM5C,YAAY2G,eAAe4H,MAAM3H,KAAK;QAC5C,IAAI5G,WAAW;gBAGFwO;YAFX,MAAME,QAAQhC,MAAMhI,MAAM,CAACwE,OAAO,GAC9B,OACA,MAAM,EAACsF,yBAAAA,MAAMM,eAAe,YAArBN,yBAAyBH,qBAAqBrO,WAAW0M,MAAMhI,MAAM,EAAE2F,KAAK,CACjF,IAAM;YAEZ,IAAIqE,yBAAAA,MAAOjM,MAAM,EAAEkF,IAAI+G,OAAO;iBACzB;gBACHD,MAAM7L,IAAI,CACR,CAAC,YAAY,EAAE5C,UAAUwM,QAAQ,CAAC,qEAAqE,CAAC;YAE5G;QACF;IACF,SAAU;QACRE,MAAMtD,IAAI;IACZ;IACA,OAAO;QAAE1D;QAAQ+I;IAAM;AACzB"}
@@ -1935,7 +1935,13 @@ function instances(scope, placed, items, perRow) {
1935
1935
  const rest = flow.filter((block)=>block.kind !== 'eyebrow' && block.kind !== 'heading');
1936
1936
  const lede = rest.filter((block)=>block.kind !== 'button');
1937
1937
  const actions = rest.filter((block)=>block.kind === 'button');
1938
- const headId = compileFlow(scope, top, 'full');
1938
+ const words = compileFlow(scope, top, 'full');
1939
+ // Kept as it is (AGL-4152), its heading runs as wide as its source holds it.
1940
+ const headId = words && scope.measure ? tree.add('muiBox', null, {
1941
+ maxWidth: wordsMeasure(scope, '100%')
1942
+ }, [
1943
+ words
1944
+ ], 'measure') : words;
1939
1945
  const ledeId = compileFlow(scope, lede, 'half');
1940
1946
  const actionsId = compileFlow(scope, actions, 'half');
1941
1947
  const under = ledeId && actionsId ? designRow(scope, [