@aglyn/plugins-ai 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-ai",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,22 +25,22 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.4.0",
29
- "@aglyn/shared-data-enums": "1.4.0",
30
- "@aglyn/shared-data-mdi": "1.4.0",
31
- "@aglyn/shared-data-types": "1.4.0",
32
- "@aglyn/shared-ui-email-campaigns": "1.4.0",
33
- "@aglyn/shared-ui-jsx": "1.4.0",
34
- "@aglyn/shared-ui-snackstack": "1.4.0",
35
- "@aglyn/shared-ui-theme": "1.4.0",
36
- "@aglyn/shared-util-email": "1.4.0",
37
- "@aglyn/shared-util-errors": "1.4.0",
38
- "@aglyn/shared-util-http": "1.4.0",
39
- "@aglyn/shared-util-timestamp": "1.4.0",
40
- "@aglyn/shared-util-tools": "1.4.0",
41
- "@aglyn/tenant-data-admin": "1.4.0",
42
- "@aglyn/tenant-feature-instance": "1.4.0",
43
- "@aglyn/tenant-runtime": "1.4.0",
28
+ "@aglyn/aglyn": "1.6.0",
29
+ "@aglyn/shared-data-enums": "1.6.0",
30
+ "@aglyn/shared-data-mdi": "1.6.0",
31
+ "@aglyn/shared-data-types": "1.6.0",
32
+ "@aglyn/shared-ui-email-campaigns": "1.6.0",
33
+ "@aglyn/shared-ui-jsx": "1.6.0",
34
+ "@aglyn/shared-ui-snackstack": "1.6.0",
35
+ "@aglyn/shared-ui-theme": "1.6.0",
36
+ "@aglyn/shared-util-email": "1.6.0",
37
+ "@aglyn/shared-util-errors": "1.6.0",
38
+ "@aglyn/shared-util-http": "1.6.0",
39
+ "@aglyn/shared-util-timestamp": "1.6.0",
40
+ "@aglyn/shared-util-tools": "1.6.0",
41
+ "@aglyn/tenant-data-admin": "1.6.0",
42
+ "@aglyn/tenant-feature-instance": "1.6.0",
43
+ "@aglyn/tenant-runtime": "1.6.0",
44
44
  "@swc/helpers": "0.5.23"
45
45
  },
46
46
  "peerDependencies": {
@@ -2,6 +2,13 @@ import type { ConsoleHostSeoZoneProps } from '@aglyn/aglyn/plugin-manager/featur
2
2
  import { type AiSeoSiteFormField } from '../model/ai-seo';
3
3
  /** What each site SEO form field is called where the proposal lists it. */
4
4
  export declare const AI_SEO_SITE_FIELD_LABELS: Record<AiSeoSiteFormField, string>;
5
+ /**
6
+ * The proposed fields that live on Setup → Business profile's Business details card
7
+ * rather than on this section (AGL-4136). The settings route each to the card
8
+ * that owns it, so they are staged there, and the note under "Put in the
9
+ * form" has to say where they went.
10
+ */
11
+ export declare const AI_SEO_BUSINESS_DETAILS_FIELDS: readonly AiSeoSiteFormField[];
5
12
  export declare function AiSeoAuditCard(props: ConsoleHostSeoZoneProps): import("react").JSX.Element;
6
13
  export declare namespace AiSeoAuditCard {
7
14
  var displayName: string;
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
17
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
18
18
  import { lockdownRefusalText, parseLockdownRefusal } from "@aglyn/aglyn";
19
19
  import { pluginDocsHelp } from "@aglyn/aglyn/app-utils/docs-help";
20
20
  import { AppLink, CardDisplay } from "@aglyn/shared-ui-jsx";
@@ -39,7 +39,9 @@ import { readEventFrames } from "./assist-jobs-drawer.component.js";
39
39
  * keywords are the ones the check was last run with (`check.keywords`).
40
40
  *
41
41
  * Nothing it shows is saved. "Put in the form" stages the site-wide proposal
42
- * in the SEO form below as unsaved edits, and the form's Update is the write.
42
+ * in the SEO forms below as unsaved edits — the name, email and phone in
43
+ * Setup → Business profile's Business details, where they are entered (AGL-4136) —
44
+ * and each form's Update is the write.
43
45
  * "Apply all" does that too, and asks the apply door to open a new
44
46
  * unpublished version for each page's content fixes and to stage each page's
45
47
  * listing for its SEO card — the live site serves none of it until a person
@@ -60,6 +62,16 @@ const ENTITY_TYPE_WORDS = {
60
62
  '1': 'An organization',
61
63
  '2': 'A person'
62
64
  };
65
+ /**
66
+ * The proposed fields that live on Setup → Business profile's Business details card
67
+ * rather than on this section (AGL-4136). The settings route each to the card
68
+ * that owns it, so they are staged there, and the note under "Put in the
69
+ * form" has to say where they went.
70
+ */ export const AI_SEO_BUSINESS_DETAILS_FIELDS = [
71
+ 'seo.entity.name',
72
+ 'seo.entity.email',
73
+ 'seo.entity.telephone'
74
+ ];
63
75
  /** One page's proposed fix, in a sentence a table cell can hold. */ function fixSummary(fix) {
64
76
  if (!fix) return '';
65
77
  const parts = [];
@@ -217,6 +229,9 @@ export function AiSeoAuditCard(props) {
217
229
  ]);
218
230
  const siteValues = (_ref2 = view == null ? void 0 : (_view_site = view.site) == null ? void 0 : _view_site.values) != null ? _ref2 : {};
219
231
  const siteFields = Object.keys(siteValues);
232
+ // Where "Put in the form" staged each proposed field (AGL-4136).
233
+ const stagedOnBusiness = siteFields.some((field)=>AI_SEO_BUSINESS_DETAILS_FIELDS.includes(field));
234
+ const stagedHere = siteFields.some((field)=>!AI_SEO_BUSINESS_DETAILS_FIELDS.includes(field));
220
235
  const stageSite = useCallback(()=>{
221
236
  if (!job || !siteFields.length) return;
222
237
  proposeDraft(siteValues, `${job.id}:site`);
@@ -413,9 +428,22 @@ export function AiSeoAuditCard(props) {
413
428
  onClick: stageSite,
414
429
  children: 'Put in the form'
415
430
  }),
416
- siteStaged === job.id ? /*#__PURE__*/ _jsx(Alert, {
431
+ siteStaged === job.id ? /*#__PURE__*/ _jsxs(Alert, {
417
432
  severity: "success",
418
- children: 'In the SEO form below as unsaved changes. Review them, then press Update.'
433
+ children: [
434
+ stagedHere ? 'In the SEO forms below as unsaved changes. Review them, then press Update.' : null,
435
+ stagedOnBusiness ? /*#__PURE__*/ _jsxs(_Fragment, {
436
+ children: [
437
+ stagedHere ? ' ' : '',
438
+ 'The name, email and phone are in Business details on ',
439
+ host ? /*#__PURE__*/ _jsx(AppLink, {
440
+ href: `/${orgSlug}/hosts/${host}/setup/business`,
441
+ children: 'Setup → Business profile'
442
+ }) : 'Setup → Business profile',
443
+ ' as unsaved changes. Review them there, then press Update.'
444
+ ]
445
+ }) : null
446
+ ]
419
447
  }) : null
420
448
  ]
421
449
  }) : null,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/ai-seo-audit-card.component.tsx"],"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'use client'\n\nimport { lockdownRefusalText, parseLockdownRefusal } from '@aglyn/aglyn'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport type { ConsoleHostSeoZoneProps } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Box,\n Button,\n CircularProgress,\n Collapse,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { AI_JOB_TERMINAL_STATUSES, type AiJobSummary } from '../model/ai-jobs.types'\nimport {\n aiSeoApplyCounts,\n aiSeoAuditView,\n type AiSeoPageFix,\n type AiSeoSiteFormField,\n} from '../model/ai-seo'\nimport { readEventFrames } from './assist-jobs-drawer.component'\n\n/**\n * SEO fixes (AGL-2910), on the site's SEO section through the `hostSeo` zone,\n * under the platform's SEO check. The check lists what is wrong for every\n * site owner; this card adds what only a model can: a person asks, and an\n * `seo` job audits the same pages through the same check, proposes a fix per\n * finding, and drafts the structured data and the agent guidance\n * `/llms.txt` leads with. The findings are never listed here — the check\n * above draws them — so this card shows the fixes, page by page. The target\n * keywords are the ones the check was last run with (`check.keywords`).\n *\n * Nothing it shows is saved. \"Put in the form\" stages the site-wide proposal\n * in the SEO form below as unsaved edits, and the form's Update is the write.\n * \"Apply all\" does that too, and asks the apply door to open a new\n * unpublished version for each page's content fixes and to stage each page's\n * listing for its SEO card — the live site serves none of it until a person\n * saves or publishes.\n */\n\n/** How many recent jobs the card reads to find this site's last audit. */\nconst RECENT_JOBS_READ = 20\n\ntype Verdict = 'checking' | 'ready' | 'hidden'\n\ninterface ApplyResult {\n versions: Array<{ screenId: string; versionId: string; name: string; fixes: number }>\n staged: string[]\n skipped: Array<{ screenId: string; reason: string }>\n}\n\nconst isTerminal = (job: AiJobSummary) => AI_JOB_TERMINAL_STATUSES.includes(job.status)\n\n/** What each site SEO form field is called where the proposal lists it. */\nexport const AI_SEO_SITE_FIELD_LABELS: Record<AiSeoSiteFormField, string> = {\n 'seo.entity.type': 'Published by',\n 'seo.entity.name': 'Name',\n 'seo.entity.description': 'Description',\n 'seo.entity.email': 'Contact email',\n 'seo.entity.telephone': 'Contact phone',\n 'seo.entity.contactType': 'Contact is for',\n 'seo.agent.whenToUse': 'When to use this site',\n 'seo.agent.howToUse': 'How an agent should call you',\n}\n\nconst ENTITY_TYPE_WORDS: Record<string, string> = { '1': 'An organization', '2': 'A person' }\n\n/** One page's proposed fix, in a sentence a table cell can hold. */\nfunction fixSummary(fix: AiSeoPageFix | undefined): string {\n if (!fix) return ''\n const parts: string[] = []\n if (fix.values.title) parts.push(`Title: ${fix.values.title}`)\n if (fix.values.description) parts.push(`Description: ${fix.values.description}`)\n const alts = fix.content.filter((entry) => entry.kind === 'image-alt').length\n if (alts) parts.push(`${alts} image ${alts === 1 ? 'description' : 'descriptions'}`)\n if (fix.content.some((entry) => entry.kind !== 'image-alt')) parts.push('One main heading')\n parts.push(...fix.guidance)\n return parts.join(' · ')\n}\n\nexport function AiSeoAuditCard(props: ConsoleHostSeoZoneProps) {\n const { hostId, orgId, orgSlug, host, proposeDraft, check } = props\n const keywords = check?.keywords ?? ''\n const { data: user } = useUser()\n const userRef = useRef(user)\n userRef.current = user\n const uid = user?.uid ?? null\n\n const [verdict, setVerdict] = useState<Verdict>('checking')\n const [notice, setNotice] = useState<string | null>(null)\n const [busy, setBusy] = useState(false)\n const [job, setJob] = useState<AiJobSummary | null>(null)\n const [siteStaged, setSiteStaged] = useState<string | null>(null)\n const [applying, setApplying] = useState(false)\n const [applied, setApplied] = useState<ApplyResult | null>(null)\n const [previewOpen, setPreviewOpen] = useState(false)\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const watchRef = useRef<AbortController | null>(null)\n\n useEffect(() => () => watchRef.current?.abort(), [])\n\n useEffect(() => {\n if (!orgId || !hostId || !uid) return\n let active = true\n setVerdict('checking')\n void (async () => {\n try {\n const response = await authorizedFetch(\n userRef.current,\n `/api/ai/jobs?orgId=${encodeURIComponent(orgId)}&limit=${RECENT_JOBS_READ}`,\n )\n if (!active) return\n if (response.status === 404 || response.status === 403) {\n setVerdict('hidden')\n return\n }\n const payload = await response.json().catch(() => null)\n if (!active) return\n if (!response.ok) {\n const locked = parseLockdownRefusal(response.status, payload)\n setNotice(\n locked\n ? lockdownRefusalText(locked)\n : String(payload?.error ?? 'The last SEO audit could not be loaded.'),\n )\n } else {\n // An audit is the SEO job whose outputs carry a report; the summary\n // does not carry a job's inputs.\n const latest = ((payload?.jobs ?? []) as AiJobSummary[]).find(\n (entry) => entry.kind === 'seo' && entry.hostId === hostId && aiSeoAuditView(entry.outputs) !== null,\n )\n if (latest) setJob(latest)\n }\n setVerdict('ready')\n } catch {\n if (!active) return\n setNotice('The last SEO audit could not be loaded.')\n setVerdict('ready')\n }\n })()\n return () => {\n active = false\n }\n }, [orgId, hostId, uid])\n\n /** Follows a job through the events route until it settles. */\n const watch = useCallback(async (jobId: string, org: string) => {\n watchRef.current?.abort()\n const controller = new AbortController()\n watchRef.current = controller\n let again = true\n while (again && !controller.signal.aborted) {\n again = false\n try {\n const response = await authorizedFetch(\n userRef.current,\n `/api/ai/jobs/${encodeURIComponent(jobId)}/events?orgId=${encodeURIComponent(org)}`,\n { signal: controller.signal },\n )\n if (!response.ok || !response.body) return\n await readEventFrames(response.body, (event) => {\n if (event['type'] === 'state') setJob(event['job'] as AiJobSummary)\n else if (event['type'] === 'reconnect') again = true\n })\n } catch {\n return\n }\n }\n }, [])\n\n // A job the card did not start, still moving, is followed too.\n const followId = job && !isTerminal(job) && !busy ? job.id : null\n useEffect(() => {\n if (followId && orgId) void watch(followId, orgId)\n }, [followId, orgId, watch])\n\n const run = useCallback(async () => {\n if (!orgId) return\n setBusy(true)\n setNotice(null)\n setApplied(null)\n setSiteStaged(null)\n setPage(0)\n try {\n const response = await authorizedFetch(userRef.current, '/api/ai/jobs', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n orgId,\n hostId,\n kind: 'seo',\n brief: 'Propose fixes for the SEO of this site',\n inputs: { target: 'site', keywords: keywords.trim() },\n }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n const locked = parseLockdownRefusal(response.status, payload)\n setNotice(\n locked\n ? lockdownRefusalText(locked)\n : String(payload?.error ?? 'The SEO audit could not be started — try again.'),\n )\n return\n }\n const next = payload?.job as AiJobSummary | undefined\n if (!next) return\n setJob(next)\n if (!isTerminal(next)) await watch(next.id, orgId)\n } catch {\n setNotice('The SEO audit could not be started — try again.')\n } finally {\n setBusy(false)\n }\n }, [orgId, hostId, keywords, watch])\n\n const view = useMemo(() => (job ? aiSeoAuditView(job.outputs) : null), [job])\n const siteValues = view?.site?.values ?? {}\n const siteFields = Object.keys(siteValues) as AiSeoSiteFormField[]\n\n const stageSite = useCallback(() => {\n if (!job || !siteFields.length) return\n proposeDraft(siteValues as Record<string, string>, `${job.id}:site`)\n setSiteStaged(job.id)\n }, [job, siteFields.length, siteValues, proposeDraft])\n\n const applyAll = useCallback(async () => {\n if (!job || !orgId) return\n setApplying(true)\n setNotice(null)\n stageSite()\n try {\n const response = await authorizedFetch(userRef.current, '/api/ai/seo/apply', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ orgId, hostId, jobId: job.id }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n const locked = parseLockdownRefusal(response.status, payload)\n setNotice(\n locked ? lockdownRefusalText(locked) : String(payload?.error ?? 'The fixes could not be applied — try again.'),\n )\n return\n }\n if (payload?.job) setJob(payload.job as AiJobSummary)\n setApplied({\n versions: payload?.versions ?? [],\n staged: payload?.staged ?? [],\n skipped: payload?.skipped ?? [],\n })\n } catch {\n setNotice('The fixes could not be applied — try again.')\n } finally {\n setApplying(false)\n }\n }, [job, orgId, hostId, stageSite])\n\n if (verdict !== 'ready') return null\n\n const running = Boolean(job && !isTerminal(job))\n const report = view?.report ?? null\n const owedBatches = report ? Math.ceil(report.queue.length / Math.max(1, report.batchSize)) : 0\n const counts = view ? aiSeoApplyCounts(view) : { pagesWithContent: 0, pagesWithValues: 0 }\n const somethingToApply = counts.pagesWithContent + counts.pagesWithValues + siteFields.length > 0\n // The pages a fix was proposed for, or is still owed to; the check above lists the rest.\n const fixRows = report\n ? report.pages.filter((entry) => view?.fixes[entry.screenId] || report.queue.includes(entry.screenId))\n : []\n const pageRows = fixRows.slice(page * pageSize, (page + 1) * pageSize)\n const names = new Map((report?.pages ?? []).map((entry) => [entry.screenId, entry]))\n const pageLink = (screenId: string, versionId: string | null, surface: 'view' | 'besigner') =>\n host && versionId\n ? `/${orgSlug}/hosts/${host}/screens/${screenId}/versions/${versionId}/${surface}`\n : null\n\n return (\n <CardDisplay\n contentGutterX\n contentGutterY\n header=\"SEO fixes\"\n help={pluginDocsHelp('aiSeo', {\n anchor: '#fix-what-the-seo-check-finds',\n excerpt:\n 'Get a proposed fix for each finding of the SEO check. Nothing changes on your live site until you save or publish.',\n })}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {keywords\n ? 'Proposes a fix for each finding of the SEO check above, using the target keywords it was run with. Nothing changes on your live site until you save or publish it.'\n : 'Proposes a fix for each finding of the SEO check above. Nothing changes on your live site until you save or publish it.'}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button variant=\"contained\" disabled={busy || running || !orgId} onClick={() => void run()}>\n {report ? 'Propose fixes again' : 'Propose fixes'}\n </Button>\n {running ? <CircularProgress size={18} aria-label=\"Proposing fixes\" /> : null}\n {running && report ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Proposing fixes: ${view?.batches ?? 0} of ${owedBatches} batches`}\n </Typography>\n ) : null}\n </Stack>\n {notice ? <Alert severity=\"warning\">{notice}</Alert> : null}\n {job?.error ? <Alert severity={job.status === 'failed' ? 'error' : 'warning'}>{job.error}</Alert> : null}\n\n {report && job ? (\n <Stack spacing={2} aria-label=\"SEO fixes\">\n {job.creditsSpent > 0 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`These fixes used ${job.creditsSpent} ${job.creditsSpent === 1 ? 'credit' : 'credits'}.`}\n </Typography>\n ) : null}\n\n {view?.site ? (\n <Stack spacing={1} aria-label=\"Structured data and agent guidance\">\n <Typography variant=\"subtitle2\">{'Structured data and AI agent guidance'}</Typography>\n {siteFields.length ? (\n siteFields.map((field) => (\n <Stack key={field} spacing={0.25}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {AI_SEO_SITE_FIELD_LABELS[field]}\n </Typography>\n <Typography variant=\"body2\" sx={{ wordBreak: 'break-word' }}>\n {field === 'seo.entity.type' ? (ENTITY_TYPE_WORDS[siteValues[field] ?? ''] ?? siteValues[field]) : siteValues[field]}\n </Typography>\n </Stack>\n ))\n ) : (\n <Typography variant=\"body2\">{'Nothing to add: the site’s structured data and guidance are already filled in.'}</Typography>\n )}\n {view.site.notes.map((note) => (\n <Typography key={note} variant=\"caption\" color=\"text.secondary\">\n {note}\n </Typography>\n ))}\n <Button size=\"small\" sx={{ alignSelf: 'flex-start' }} onClick={() => setPreviewOpen((open) => !open)}>\n {previewOpen ? 'Hide the /llms.txt preview' : 'Preview /llms.txt'}\n </Button>\n <Collapse in={previewOpen} unmountOnExit>\n <Box\n component=\"pre\"\n sx={{ m: 0, p: 1.5, bgcolor: 'action.hover', borderRadius: 1, whiteSpace: 'pre-wrap', fontSize: 12 }}\n >\n {view.site.llmsPreview}\n </Box>\n </Collapse>\n <Button\n size=\"small\"\n variant=\"outlined\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={!siteFields.length || siteStaged === job.id}\n onClick={stageSite}\n >\n {'Put in the form'}\n </Button>\n {siteStaged === job.id ? (\n <Alert severity=\"success\">{'In the SEO form below as unsaved changes. Review them, then press Update.'}</Alert>\n ) : null}\n </Stack>\n ) : null}\n\n {fixRows.length ? (\n <Box>\n <ScrollTable size=\"small\" aria-label=\"Proposed fixes\">\n <TableHead>\n <TableRow>\n <TableCell>{'Page'}</TableCell>\n <TableCell>{'Proposed'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {pageRows.map((row) => (\n <TableRow key={row.screenId}>\n <TableCell>\n <Typography variant=\"body2\">{row.name}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {row.path}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\" sx={{ wordBreak: 'break-word' }}>\n {fixSummary(view?.fixes[row.screenId]) || (running ? 'Being proposed…' : '')}\n </Typography>\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={pageRows.length}\n count={fixRows.length}\n onPageChange={setPage}\n onPageSizeChange={(size) => {\n setPageSize(size)\n setPage(0)\n }}\n />\n </Box>\n ) : (\n <Typography variant=\"body2\">\n {report.pages.length\n ? 'No page needs a written fix.'\n : 'This site has no published public pages to fix.'}\n </Typography>\n )}\n\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Apply all opens a new draft version of each page with content fixes, puts proposed titles and descriptions in each page’s SEO card, and puts the structured data and guidance in the form below. You review and save or publish each of them.'}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button\n variant=\"contained\"\n disabled={applying || running || job.status !== 'done' || !view?.complete || !somethingToApply}\n onClick={() => void applyAll()}\n >\n {'Apply all as drafts'}\n </Button>\n {applying ? <CircularProgress size={18} aria-label=\"Applying the fixes\" /> : null}\n </Stack>\n </Stack>\n\n {applied ? (\n <Stack spacing={1} aria-label=\"Applied fixes\">\n {applied.versions.map((entry) => {\n const href = pageLink(entry.screenId, entry.versionId, 'besigner')\n return (\n <Typography key={entry.screenId} variant=\"body2\">\n {href ? (\n <AppLink componentVariant=\"naked\" href={href}>\n {`Open the draft of ${entry.name}`}\n </AppLink>\n ) : (\n `A draft of ${entry.name} is ready`\n )}\n </Typography>\n )\n })}\n {applied.staged.map((screenId) => {\n const audited = names.get(screenId)\n const href = pageLink(screenId, audited?.versionId ?? null, 'view')\n return (\n <Typography key={`staged:${screenId}`} variant=\"body2\">\n {href ? (\n <AppLink componentVariant=\"naked\" href={href}>\n {`Review the listing for ${audited?.name ?? screenId}`}\n </AppLink>\n ) : (\n `A listing for ${audited?.name ?? screenId} waits in its SEO card`\n )}\n </Typography>\n )\n })}\n {applied.skipped.map((entry) => (\n <Typography key={`skipped:${entry.screenId}`} variant=\"caption\" color=\"text.secondary\">\n {`${names.get(entry.screenId)?.name ?? entry.screenId}: ${entry.reason}`}\n </Typography>\n ))}\n </Stack>\n ) : null}\n </Stack>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nAiSeoAuditCard.displayName = 'AiSeoAuditCard'\n\nexport default AiSeoAuditCard\n"],"names":["lockdownRefusalText","parseLockdownRefusal","pluginDocsHelp","AppLink","CardDisplay","ListPagination","ScrollTable","TABLE_PAGE_SIZE_DEFAULT","authorizedFetch","useUser","Alert","Box","Button","CircularProgress","Collapse","Stack","TableBody","TableCell","TableHead","TableRow","Typography","useCallback","useEffect","useMemo","useRef","useState","AI_JOB_TERMINAL_STATUSES","aiSeoApplyCounts","aiSeoAuditView","readEventFrames","RECENT_JOBS_READ","isTerminal","job","includes","status","AI_SEO_SITE_FIELD_LABELS","ENTITY_TYPE_WORDS","fixSummary","fix","parts","values","title","push","description","alts","content","filter","entry","kind","length","some","guidance","join","AiSeoAuditCard","props","view","hostId","orgId","orgSlug","host","proposeDraft","check","keywords","data","user","userRef","current","uid","verdict","setVerdict","notice","setNotice","busy","setBusy","setJob","siteStaged","setSiteStaged","applying","setApplying","applied","setApplied","previewOpen","setPreviewOpen","page","setPage","pageSize","setPageSize","watchRef","abort","active","response","encodeURIComponent","payload","json","catch","ok","locked","String","error","latest","jobs","find","outputs","watch","jobId","org","controller","AbortController","again","signal","aborted","body","event","followId","id","run","method","headers","JSON","stringify","brief","inputs","target","trim","next","siteValues","site","siteFields","Object","keys","stageSite","applyAll","versions","staged","skipped","running","Boolean","report","owedBatches","Math","ceil","queue","max","batchSize","counts","pagesWithContent","pagesWithValues","somethingToApply","fixRows","pages","fixes","screenId","pageRows","slice","names","Map","map","pageLink","versionId","surface","contentGutterX","contentGutterY","header","help","anchor","excerpt","spacing","variant","color","direction","sx","alignItems","disabled","onClick","size","aria-label","batches","severity","creditsSpent","field","wordBreak","notes","note","alignSelf","open","in","unmountOnExit","component","m","p","bgcolor","borderRadius","whiteSpace","fontSize","llmsPreview","row","name","path","rowCount","count","onPageChange","onPageSizeChange","complete","href","componentVariant","audited","get","reason","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,mBAAmB,EAAEC,oBAAoB,QAAQ,eAAc;AACxE,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AACzE,SAASC,wBAAwB,QAA2B,4BAAwB;AACpF,SACEC,gBAAgB,EAChBC,cAAc,QAGT,qBAAiB;AACxB,SAASC,eAAe,QAAQ,oCAAgC;AAEhE;;;;;;;;;;;;;;;;CAgBC,GAED,wEAAwE,GACxE,MAAMC,mBAAmB;AAUzB,MAAMC,aAAa,CAACC,MAAsBN,yBAAyBO,QAAQ,CAACD,IAAIE,MAAM;AAEtF,yEAAyE,GACzE,OAAO,MAAMC,2BAA+D;IAC1E,mBAAmB;IACnB,mBAAmB;IACnB,0BAA0B;IAC1B,oBAAoB;IACpB,wBAAwB;IACxB,0BAA0B;IAC1B,uBAAuB;IACvB,sBAAsB;AACxB,EAAC;AAED,MA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src/lib/components/ai-seo-audit-card.component.tsx"],"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'use client'\n\nimport { lockdownRefusalText, parseLockdownRefusal } from '@aglyn/aglyn'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport type { ConsoleHostSeoZoneProps } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Box,\n Button,\n CircularProgress,\n Collapse,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { AI_JOB_TERMINAL_STATUSES, type AiJobSummary } from '../model/ai-jobs.types'\nimport {\n aiSeoApplyCounts,\n aiSeoAuditView,\n type AiSeoPageFix,\n type AiSeoSiteFormField,\n} from '../model/ai-seo'\nimport { readEventFrames } from './assist-jobs-drawer.component'\n\n/**\n * SEO fixes (AGL-2910), on the site's SEO section through the `hostSeo` zone,\n * under the platform's SEO check. The check lists what is wrong for every\n * site owner; this card adds what only a model can: a person asks, and an\n * `seo` job audits the same pages through the same check, proposes a fix per\n * finding, and drafts the structured data and the agent guidance\n * `/llms.txt` leads with. The findings are never listed here — the check\n * above draws them — so this card shows the fixes, page by page. The target\n * keywords are the ones the check was last run with (`check.keywords`).\n *\n * Nothing it shows is saved. \"Put in the form\" stages the site-wide proposal\n * in the SEO forms below as unsaved edits — the name, email and phone in\n * Setup → Business profile's Business details, where they are entered (AGL-4136) —\n * and each form's Update is the write.\n * \"Apply all\" does that too, and asks the apply door to open a new\n * unpublished version for each page's content fixes and to stage each page's\n * listing for its SEO card — the live site serves none of it until a person\n * saves or publishes.\n */\n\n/** How many recent jobs the card reads to find this site's last audit. */\nconst RECENT_JOBS_READ = 20\n\ntype Verdict = 'checking' | 'ready' | 'hidden'\n\ninterface ApplyResult {\n versions: Array<{ screenId: string; versionId: string; name: string; fixes: number }>\n staged: string[]\n skipped: Array<{ screenId: string; reason: string }>\n}\n\nconst isTerminal = (job: AiJobSummary) => AI_JOB_TERMINAL_STATUSES.includes(job.status)\n\n/** What each site SEO form field is called where the proposal lists it. */\nexport const AI_SEO_SITE_FIELD_LABELS: Record<AiSeoSiteFormField, string> = {\n 'seo.entity.type': 'Published by',\n 'seo.entity.name': 'Name',\n 'seo.entity.description': 'Description',\n 'seo.entity.email': 'Contact email',\n 'seo.entity.telephone': 'Contact phone',\n 'seo.entity.contactType': 'Contact is for',\n 'seo.agent.whenToUse': 'When to use this site',\n 'seo.agent.howToUse': 'How an agent should call you',\n}\n\nconst ENTITY_TYPE_WORDS: Record<string, string> = { '1': 'An organization', '2': 'A person' }\n\n/**\n * The proposed fields that live on Setup → Business profile's Business details card\n * rather than on this section (AGL-4136). The settings route each to the card\n * that owns it, so they are staged there, and the note under \"Put in the\n * form\" has to say where they went.\n */\nexport const AI_SEO_BUSINESS_DETAILS_FIELDS: readonly AiSeoSiteFormField[] = [\n 'seo.entity.name',\n 'seo.entity.email',\n 'seo.entity.telephone',\n]\n\n/** One page's proposed fix, in a sentence a table cell can hold. */\nfunction fixSummary(fix: AiSeoPageFix | undefined): string {\n if (!fix) return ''\n const parts: string[] = []\n if (fix.values.title) parts.push(`Title: ${fix.values.title}`)\n if (fix.values.description) parts.push(`Description: ${fix.values.description}`)\n const alts = fix.content.filter((entry) => entry.kind === 'image-alt').length\n if (alts) parts.push(`${alts} image ${alts === 1 ? 'description' : 'descriptions'}`)\n if (fix.content.some((entry) => entry.kind !== 'image-alt')) parts.push('One main heading')\n parts.push(...fix.guidance)\n return parts.join(' · ')\n}\n\nexport function AiSeoAuditCard(props: ConsoleHostSeoZoneProps) {\n const { hostId, orgId, orgSlug, host, proposeDraft, check } = props\n const keywords = check?.keywords ?? ''\n const { data: user } = useUser()\n const userRef = useRef(user)\n userRef.current = user\n const uid = user?.uid ?? null\n\n const [verdict, setVerdict] = useState<Verdict>('checking')\n const [notice, setNotice] = useState<string | null>(null)\n const [busy, setBusy] = useState(false)\n const [job, setJob] = useState<AiJobSummary | null>(null)\n const [siteStaged, setSiteStaged] = useState<string | null>(null)\n const [applying, setApplying] = useState(false)\n const [applied, setApplied] = useState<ApplyResult | null>(null)\n const [previewOpen, setPreviewOpen] = useState(false)\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const watchRef = useRef<AbortController | null>(null)\n\n useEffect(() => () => watchRef.current?.abort(), [])\n\n useEffect(() => {\n if (!orgId || !hostId || !uid) return\n let active = true\n setVerdict('checking')\n void (async () => {\n try {\n const response = await authorizedFetch(\n userRef.current,\n `/api/ai/jobs?orgId=${encodeURIComponent(orgId)}&limit=${RECENT_JOBS_READ}`,\n )\n if (!active) return\n if (response.status === 404 || response.status === 403) {\n setVerdict('hidden')\n return\n }\n const payload = await response.json().catch(() => null)\n if (!active) return\n if (!response.ok) {\n const locked = parseLockdownRefusal(response.status, payload)\n setNotice(\n locked\n ? lockdownRefusalText(locked)\n : String(payload?.error ?? 'The last SEO audit could not be loaded.'),\n )\n } else {\n // An audit is the SEO job whose outputs carry a report; the summary\n // does not carry a job's inputs.\n const latest = ((payload?.jobs ?? []) as AiJobSummary[]).find(\n (entry) => entry.kind === 'seo' && entry.hostId === hostId && aiSeoAuditView(entry.outputs) !== null,\n )\n if (latest) setJob(latest)\n }\n setVerdict('ready')\n } catch {\n if (!active) return\n setNotice('The last SEO audit could not be loaded.')\n setVerdict('ready')\n }\n })()\n return () => {\n active = false\n }\n }, [orgId, hostId, uid])\n\n /** Follows a job through the events route until it settles. */\n const watch = useCallback(async (jobId: string, org: string) => {\n watchRef.current?.abort()\n const controller = new AbortController()\n watchRef.current = controller\n let again = true\n while (again && !controller.signal.aborted) {\n again = false\n try {\n const response = await authorizedFetch(\n userRef.current,\n `/api/ai/jobs/${encodeURIComponent(jobId)}/events?orgId=${encodeURIComponent(org)}`,\n { signal: controller.signal },\n )\n if (!response.ok || !response.body) return\n await readEventFrames(response.body, (event) => {\n if (event['type'] === 'state') setJob(event['job'] as AiJobSummary)\n else if (event['type'] === 'reconnect') again = true\n })\n } catch {\n return\n }\n }\n }, [])\n\n // A job the card did not start, still moving, is followed too.\n const followId = job && !isTerminal(job) && !busy ? job.id : null\n useEffect(() => {\n if (followId && orgId) void watch(followId, orgId)\n }, [followId, orgId, watch])\n\n const run = useCallback(async () => {\n if (!orgId) return\n setBusy(true)\n setNotice(null)\n setApplied(null)\n setSiteStaged(null)\n setPage(0)\n try {\n const response = await authorizedFetch(userRef.current, '/api/ai/jobs', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n orgId,\n hostId,\n kind: 'seo',\n brief: 'Propose fixes for the SEO of this site',\n inputs: { target: 'site', keywords: keywords.trim() },\n }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n const locked = parseLockdownRefusal(response.status, payload)\n setNotice(\n locked\n ? lockdownRefusalText(locked)\n : String(payload?.error ?? 'The SEO audit could not be started — try again.'),\n )\n return\n }\n const next = payload?.job as AiJobSummary | undefined\n if (!next) return\n setJob(next)\n if (!isTerminal(next)) await watch(next.id, orgId)\n } catch {\n setNotice('The SEO audit could not be started — try again.')\n } finally {\n setBusy(false)\n }\n }, [orgId, hostId, keywords, watch])\n\n const view = useMemo(() => (job ? aiSeoAuditView(job.outputs) : null), [job])\n const siteValues = view?.site?.values ?? {}\n const siteFields = Object.keys(siteValues) as AiSeoSiteFormField[]\n // Where \"Put in the form\" staged each proposed field (AGL-4136).\n const stagedOnBusiness = siteFields.some((field) => AI_SEO_BUSINESS_DETAILS_FIELDS.includes(field))\n const stagedHere = siteFields.some((field) => !AI_SEO_BUSINESS_DETAILS_FIELDS.includes(field))\n\n const stageSite = useCallback(() => {\n if (!job || !siteFields.length) return\n proposeDraft(siteValues as Record<string, string>, `${job.id}:site`)\n setSiteStaged(job.id)\n }, [job, siteFields.length, siteValues, proposeDraft])\n\n const applyAll = useCallback(async () => {\n if (!job || !orgId) return\n setApplying(true)\n setNotice(null)\n stageSite()\n try {\n const response = await authorizedFetch(userRef.current, '/api/ai/seo/apply', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ orgId, hostId, jobId: job.id }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n const locked = parseLockdownRefusal(response.status, payload)\n setNotice(\n locked ? lockdownRefusalText(locked) : String(payload?.error ?? 'The fixes could not be applied — try again.'),\n )\n return\n }\n if (payload?.job) setJob(payload.job as AiJobSummary)\n setApplied({\n versions: payload?.versions ?? [],\n staged: payload?.staged ?? [],\n skipped: payload?.skipped ?? [],\n })\n } catch {\n setNotice('The fixes could not be applied — try again.')\n } finally {\n setApplying(false)\n }\n }, [job, orgId, hostId, stageSite])\n\n if (verdict !== 'ready') return null\n\n const running = Boolean(job && !isTerminal(job))\n const report = view?.report ?? null\n const owedBatches = report ? Math.ceil(report.queue.length / Math.max(1, report.batchSize)) : 0\n const counts = view ? aiSeoApplyCounts(view) : { pagesWithContent: 0, pagesWithValues: 0 }\n const somethingToApply = counts.pagesWithContent + counts.pagesWithValues + siteFields.length > 0\n // The pages a fix was proposed for, or is still owed to; the check above lists the rest.\n const fixRows = report\n ? report.pages.filter((entry) => view?.fixes[entry.screenId] || report.queue.includes(entry.screenId))\n : []\n const pageRows = fixRows.slice(page * pageSize, (page + 1) * pageSize)\n const names = new Map((report?.pages ?? []).map((entry) => [entry.screenId, entry]))\n const pageLink = (screenId: string, versionId: string | null, surface: 'view' | 'besigner') =>\n host && versionId\n ? `/${orgSlug}/hosts/${host}/screens/${screenId}/versions/${versionId}/${surface}`\n : null\n\n return (\n <CardDisplay\n contentGutterX\n contentGutterY\n header=\"SEO fixes\"\n help={pluginDocsHelp('aiSeo', {\n anchor: '#fix-what-the-seo-check-finds',\n excerpt:\n 'Get a proposed fix for each finding of the SEO check. Nothing changes on your live site until you save or publish.',\n })}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {keywords\n ? 'Proposes a fix for each finding of the SEO check above, using the target keywords it was run with. Nothing changes on your live site until you save or publish it.'\n : 'Proposes a fix for each finding of the SEO check above. Nothing changes on your live site until you save or publish it.'}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button variant=\"contained\" disabled={busy || running || !orgId} onClick={() => void run()}>\n {report ? 'Propose fixes again' : 'Propose fixes'}\n </Button>\n {running ? <CircularProgress size={18} aria-label=\"Proposing fixes\" /> : null}\n {running && report ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Proposing fixes: ${view?.batches ?? 0} of ${owedBatches} batches`}\n </Typography>\n ) : null}\n </Stack>\n {notice ? <Alert severity=\"warning\">{notice}</Alert> : null}\n {job?.error ? <Alert severity={job.status === 'failed' ? 'error' : 'warning'}>{job.error}</Alert> : null}\n\n {report && job ? (\n <Stack spacing={2} aria-label=\"SEO fixes\">\n {job.creditsSpent > 0 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`These fixes used ${job.creditsSpent} ${job.creditsSpent === 1 ? 'credit' : 'credits'}.`}\n </Typography>\n ) : null}\n\n {view?.site ? (\n <Stack spacing={1} aria-label=\"Structured data and agent guidance\">\n <Typography variant=\"subtitle2\">{'Structured data and AI agent guidance'}</Typography>\n {siteFields.length ? (\n siteFields.map((field) => (\n <Stack key={field} spacing={0.25}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {AI_SEO_SITE_FIELD_LABELS[field]}\n </Typography>\n <Typography variant=\"body2\" sx={{ wordBreak: 'break-word' }}>\n {field === 'seo.entity.type' ? (ENTITY_TYPE_WORDS[siteValues[field] ?? ''] ?? siteValues[field]) : siteValues[field]}\n </Typography>\n </Stack>\n ))\n ) : (\n <Typography variant=\"body2\">{'Nothing to add: the site’s structured data and guidance are already filled in.'}</Typography>\n )}\n {view.site.notes.map((note) => (\n <Typography key={note} variant=\"caption\" color=\"text.secondary\">\n {note}\n </Typography>\n ))}\n <Button size=\"small\" sx={{ alignSelf: 'flex-start' }} onClick={() => setPreviewOpen((open) => !open)}>\n {previewOpen ? 'Hide the /llms.txt preview' : 'Preview /llms.txt'}\n </Button>\n <Collapse in={previewOpen} unmountOnExit>\n <Box\n component=\"pre\"\n sx={{ m: 0, p: 1.5, bgcolor: 'action.hover', borderRadius: 1, whiteSpace: 'pre-wrap', fontSize: 12 }}\n >\n {view.site.llmsPreview}\n </Box>\n </Collapse>\n <Button\n size=\"small\"\n variant=\"outlined\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={!siteFields.length || siteStaged === job.id}\n onClick={stageSite}\n >\n {'Put in the form'}\n </Button>\n {siteStaged === job.id ? (\n <Alert severity=\"success\">\n {stagedHere\n ? 'In the SEO forms below as unsaved changes. Review them, then press Update.'\n : null}\n {stagedOnBusiness ? (\n <>\n {stagedHere ? ' ' : ''}\n {'The name, email and phone are in Business details on '}\n {host ? (\n <AppLink href={`/${orgSlug}/hosts/${host}/setup/business`}>{'Setup → Business profile'}</AppLink>\n ) : (\n 'Setup → Business profile'\n )}\n {' as unsaved changes. Review them there, then press Update.'}\n </>\n ) : null}\n </Alert>\n ) : null}\n </Stack>\n ) : null}\n\n {fixRows.length ? (\n <Box>\n <ScrollTable size=\"small\" aria-label=\"Proposed fixes\">\n <TableHead>\n <TableRow>\n <TableCell>{'Page'}</TableCell>\n <TableCell>{'Proposed'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {pageRows.map((row) => (\n <TableRow key={row.screenId}>\n <TableCell>\n <Typography variant=\"body2\">{row.name}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {row.path}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\" sx={{ wordBreak: 'break-word' }}>\n {fixSummary(view?.fixes[row.screenId]) || (running ? 'Being proposed…' : '')}\n </Typography>\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={pageRows.length}\n count={fixRows.length}\n onPageChange={setPage}\n onPageSizeChange={(size) => {\n setPageSize(size)\n setPage(0)\n }}\n />\n </Box>\n ) : (\n <Typography variant=\"body2\">\n {report.pages.length\n ? 'No page needs a written fix.'\n : 'This site has no published public pages to fix.'}\n </Typography>\n )}\n\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Apply all opens a new draft version of each page with content fixes, puts proposed titles and descriptions in each page’s SEO card, and puts the structured data and guidance in the form below. You review and save or publish each of them.'}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button\n variant=\"contained\"\n disabled={applying || running || job.status !== 'done' || !view?.complete || !somethingToApply}\n onClick={() => void applyAll()}\n >\n {'Apply all as drafts'}\n </Button>\n {applying ? <CircularProgress size={18} aria-label=\"Applying the fixes\" /> : null}\n </Stack>\n </Stack>\n\n {applied ? (\n <Stack spacing={1} aria-label=\"Applied fixes\">\n {applied.versions.map((entry) => {\n const href = pageLink(entry.screenId, entry.versionId, 'besigner')\n return (\n <Typography key={entry.screenId} variant=\"body2\">\n {href ? (\n <AppLink componentVariant=\"naked\" href={href}>\n {`Open the draft of ${entry.name}`}\n </AppLink>\n ) : (\n `A draft of ${entry.name} is ready`\n )}\n </Typography>\n )\n })}\n {applied.staged.map((screenId) => {\n const audited = names.get(screenId)\n const href = pageLink(screenId, audited?.versionId ?? null, 'view')\n return (\n <Typography key={`staged:${screenId}`} variant=\"body2\">\n {href ? (\n <AppLink componentVariant=\"naked\" href={href}>\n {`Review the listing for ${audited?.name ?? screenId}`}\n </AppLink>\n ) : (\n `A listing for ${audited?.name ?? screenId} waits in its SEO card`\n )}\n </Typography>\n )\n })}\n {applied.skipped.map((entry) => (\n <Typography key={`skipped:${entry.screenId}`} variant=\"caption\" color=\"text.secondary\">\n {`${names.get(entry.screenId)?.name ?? entry.screenId}: ${entry.reason}`}\n </Typography>\n ))}\n </Stack>\n ) : null}\n </Stack>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nAiSeoAuditCard.displayName = 'AiSeoAuditCard'\n\nexport default AiSeoAuditCard\n"],"names":["lockdownRefusalText","parseLockdownRefusal","pluginDocsHelp","AppLink","CardDisplay","ListPagination","ScrollTable","TABLE_PAGE_SIZE_DEFAULT","authorizedFetch","useUser","Alert","Box","Button","CircularProgress","Collapse","Stack","TableBody","TableCell","TableHead","TableRow","Typography","useCallback","useEffect","useMemo","useRef","useState","AI_JOB_TERMINAL_STATUSES","aiSeoApplyCounts","aiSeoAuditView","readEventFrames","RECENT_JOBS_READ","isTerminal","job","includes","status","AI_SEO_SITE_FIELD_LABELS","ENTITY_TYPE_WORDS","AI_SEO_BUSINESS_DETAILS_FIELDS","fixSummary","fix","parts","values","title","push","description","alts","content","filter","entry","kind","length","some","guidance","join","AiSeoAuditCard","props","view","hostId","orgId","orgSlug","host","proposeDraft","check","keywords","data","user","userRef","current","uid","verdict","setVerdict","notice","setNotice","busy","setBusy","setJob","siteStaged","setSiteStaged","applying","setApplying","applied","setApplied","previewOpen","setPreviewOpen","page","setPage","pageSize","setPageSize","watchRef","abort","active","response","encodeURIComponent","payload","json","catch","ok","locked","String","error","latest","jobs","find","outputs","watch","jobId","org","controller","AbortController","again","signal","aborted","body","event","followId","id","run","method","headers","JSON","stringify","brief","inputs","target","trim","next","siteValues","site","siteFields","Object","keys","stagedOnBusiness","field","stagedHere","stageSite","applyAll","versions","staged","skipped","running","Boolean","report","owedBatches","Math","ceil","queue","max","batchSize","counts","pagesWithContent","pagesWithValues","somethingToApply","fixRows","pages","fixes","screenId","pageRows","slice","names","Map","map","pageLink","versionId","surface","contentGutterX","contentGutterY","header","help","anchor","excerpt","spacing","variant","color","direction","sx","alignItems","disabled","onClick","size","aria-label","batches","severity","creditsSpent","wordBreak","notes","note","alignSelf","open","in","unmountOnExit","component","m","p","bgcolor","borderRadius","whiteSpace","fontSize","llmsPreview","href","row","name","path","rowCount","count","onPageChange","onPageSizeChange","complete","componentVariant","audited","get","reason","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,mBAAmB,EAAEC,oBAAoB,QAAQ,eAAc;AACxE,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AACzE,SAASC,wBAAwB,QAA2B,4BAAwB;AACpF,SACEC,gBAAgB,EAChBC,cAAc,QAGT,qBAAiB;AACxB,SAASC,eAAe,QAAQ,oCAAgC;AAEhE;;;;;;;;;;;;;;;;;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,MAAM;oCAC5D,qBACE,KAAC9I;wCAAsCuJ,SAAQ;kDAC5C2B,qBACC,KAACnM;4CAAQ4M,kBAAiB;4CAAQT,MAAMA;sDACrC,CAAC,uBAAuB,WAAEU,2BAAAA,QAASR,IAAI,oBAAI7C,UAAU;6CAGxD,CAAC,cAAc,WAAEqD,2BAAAA,QAASR,IAAI,oBAAI7C,SAAS,sBAAsB,CAAC;uCANrD,CAAC,OAAO,EAAEA,UAAU;gCAUzC;gCACC3E,QAAQ0D,OAAO,CAACsB,GAAG,CAAC,CAAChH;;wCAEd8G;yDADN,KAAC1I;wCAA6CuJ,SAAQ;wCAAUC,OAAM;kDACnE,YAAGd,aAAAA,MAAMmD,GAAG,CAACjK,MAAM2G,QAAQ,sBAAxBG,WAA2B0C,IAAI,mBAAIxJ,MAAM2G,QAAQ,CAAC,EAAE,EAAE3G,MAAMkK,MAAM,EAAE;uCADzD,CAAC,QAAQ,EAAElK,MAAM2G,QAAQ,EAAE;;;6BAK9C;;qBAEJ;;;;AAId;AACArG,eAAe6J,WAAW,GAAG;AAE7B,eAAe7J,eAAc"}
@@ -17,7 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  */ import { formPeriodKey, formStatsTotals } from "@aglyn/aglyn/app-utils/forms";
18
18
  import { PLUGIN_FIGURE_MAX_ROWS, pluginFigureChange, pluginFigureDay, pluginFigureWindows, registerPluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
19
19
  import { AI_PLUGIN_ID } from "../constants.js";
20
- import { FORMS_WEEKLY_SUMMARY, SOURCES_WEEKLY_SUMMARY, TOP_PAGES_WEEKLY_SUMMARY, TRAFFIC_WEEKLY_SUMMARY } from "./ai-figure-summaries.js";
20
+ import { FORMS_WEEKLY_SUMMARY, SOURCES_WEEKLY_SUMMARY, TOP_PAGES_WEEKLY_SUMMARY, TRAFFIC_DAILY_WEEKLY_SUMMARY, TRAFFIC_WEEKLY_SUMMARY } from "./ai-figure-summaries.js";
21
21
  /** The traffic windows: the Traffic card's own ranges. */ export const AI_TRAFFIC_WINDOWS = [
22
22
  7,
23
23
  14,
@@ -335,7 +335,8 @@ export function trafficFigureReaders(firestore) {
335
335
  id: 'traffic.daily',
336
336
  label: 'Traffic by day',
337
337
  description: 'Page views and visitors on each day of the window, oldest first, for spotting a day that stood out.',
338
- windows: AI_TRAFFIC_DAILY_WINDOWS
338
+ windows: AI_TRAFFIC_DAILY_WINDOWS,
339
+ weeklySummary: TRAFFIC_DAILY_WEEKLY_SUMMARY
339
340
  }, async (db, request)=>{
340
341
  const ids = [
341
342
  ...dayIds(request.now, request.days).current
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-readers.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 { formPeriodKey, formStatsTotals, type FormStats } from '@aglyn/aglyn/app-utils/forms'\nimport {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureChange,\n pluginFigureDay,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRead,\n type PluginFigureRequest,\n type PluginFigureRow,\n type PluginFigureTable,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { AI_PLUGIN_ID } from '../constants'\nimport {\n FORMS_WEEKLY_SUMMARY,\n SOURCES_WEEKLY_SUMMARY,\n TOP_PAGES_WEEKLY_SUMMARY,\n TRAFFIC_WEEKLY_SUMMARY,\n} from './ai-figure-summaries'\n\n/**\n * The figure readers this plugin registers for records the PLATFORM keeps\n * (AGL-2915): a site's page-view counters and its forms' counters. Every\n * other reader an insight reads is registered by the plugin that owns its\n * records — commerce, bookings, marketing, the workspace's datasets — on the\n * `plugin-figures` seam, and nothing here reads their documents.\n *\n * Each reader answers with one compact table of aggregates, read-only and\n * about nobody: counts, sums and rates, labeled by a page path, a form's name\n * or a referring site — never a visitor or a submission.\n *\n * The readers use the arithmetic their console cards use: the Traffic card's\n * windows and change (`pluginFigureWindows`, `pluginFigureChange`, which are\n * that card's split and delta), and the forms plugin's month counters through\n * `formStatsTotals`, the one function every forms surface windows by.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** How a reader reaches Firestore: resolved when it reads, never when it registers. */\nexport type AiFigureFirestore = () => Firestore\n\n/** The traffic windows: the Traffic card's own ranges. */\nexport const AI_TRAFFIC_WINDOWS: readonly number[] = [7, 14, 30, 90]\n\n/** A day-by-day table fits a table's row bound only over a short window. */\nexport const AI_TRAFFIC_DAILY_WINDOWS: readonly number[] = [7, 14]\n\n/** Pages a pages table lists; the rest are counted in `omitted`. */\nexport const AI_TRAFFIC_TOP_PAGES = 10\n\n/** Referring sites, and campaign sources and campaigns, a sources table lists. */\nexport const AI_TRAFFIC_TOP_REFERRERS = 8\nexport const AI_TRAFFIC_TOP_CAMPAIGNS = 5\n\n/** Forms a forms table reads. */\nexport const AI_FORMS_READ_LIMIT = 100\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nconst num = (value: unknown): number => {\n const parsed = typeof value === 'number' ? value : Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\nconst round1 = (value: number): number => Math.round(value * 10) / 10\n\nconst share = (part: number, whole: number): number | null => (whole > 0 ? round1((part / whole) * 100) : null)\n\nfunction refused(status: 400 | 403 | 404, error: string): PluginFigureRead {\n return { ok: false, status, error }\n}\n\n/** A window's days as the table's period, oldest to newest. */\nfunction periodOf(request: PluginFigureRequest): PluginFigureTable['period'] {\n const { current } = pluginFigureWindows(request.now, request.days)\n return { from: current.from, to: current.to, days: request.days }\n}\n\n/** Every day id of the window and the one before it, newest first. */\nfunction dayIds(now: Date, days: number): { current: string[]; previous: string[] } {\n const { current, previous } = pluginFigureWindows(now, days)\n const walk = (startMs: number, endMs: number): string[] => {\n const ids: string[] = []\n for (let at = endMs - 86_400_000; at >= startMs; at -= 86_400_000) ids.push(pluginFigureDay(new Date(at)))\n return ids\n }\n return { current: walk(current.startMs, current.endMs), previous: walk(previous.startMs, previous.endMs) }\n}\n\n// ── Traffic ───────────────────────────────────────────────────────────────\n\ninterface TrafficDay {\n total: number\n visitors: number\n paths: Record<string, number>\n referrers: Record<string, number>\n utm: Record<string, Record<string, number>>\n}\n\nconst counts = (value: unknown): Record<string, number> => {\n const out: Record<string, number> = {}\n if (!value || typeof value !== 'object') return out\n for (const [key, count] of Object.entries(value as Record<string, unknown>)) {\n const n = num(count)\n if (n > 0) out[key] = n\n }\n return out\n}\n\nasync function readTrafficDays(\n firestore: Firestore,\n hostId: string,\n ids: readonly string[],\n): Promise<TrafficDay[]> {\n if (!ids.length) return []\n const collection = firestore.collection('hosts').doc(hostId).collection('analytics')\n const snapshots = await firestore.getAll(...ids.map((id) => collection.doc(id)))\n return snapshots.map((snapshot) => {\n const data = (snapshot.exists ? snapshot.data() : null) ?? {}\n const utm: Record<string, Record<string, number>> = {}\n for (const [param, values] of Object.entries((data['utm'] ?? {}) as Record<string, unknown>)) {\n utm[param] = counts(values)\n }\n return {\n total: num(data['total']),\n visitors: num(data['visitors']),\n paths: counts(data['paths']),\n referrers: counts(data['referrers']),\n utm,\n }\n })\n}\n\nfunction sumMaps(days: readonly TrafficDay[], pick: (day: TrafficDay) => Record<string, number>): Map<string, number> {\n const totals = new Map<string, number>()\n for (const day of days) {\n for (const [key, count] of Object.entries(pick(day))) totals.set(key, (totals.get(key) ?? 0) + count)\n }\n return totals\n}\n\nconst ranked = (totals: Map<string, number>): Array<[string, number]> =>\n [...totals.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n\nfunction siteReader(\n base: Omit<PluginFigureReader, 'read' | 'scope' | 'plugin'>,\n read: (firestore: Firestore, request: PluginFigureRequest & { hostId: string }) => Promise<PluginFigureRead>,\n firestore: AiFigureFirestore,\n plugin: string | null,\n): PluginFigureReader {\n return {\n ...base,\n scope: 'site',\n plugin,\n read: async (request) => {\n if (!request.hostId) return refused(400, 'Open a site to read its figures')\n if (!base.windows.includes(request.days)) return refused(400, 'That window is not one this reader covers')\n return read(firestore(), { ...request, hostId: request.hostId })\n },\n }\n}\n\nexport function trafficFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n const source = { label: 'Analytics', path: 'analytics' }\n const visitorsNote =\n 'Visitors are counted once per browser tab per day, so one person on two days counts twice.'\n return [\n siteReader(\n {\n id: 'traffic.summary',\n label: 'Traffic',\n description:\n 'Page views, visitors and views a day on the site over the window, each beside the window before it and the change.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TRAFFIC_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const total = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.total, 0)\n const visitors = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.visitors, 0)\n const views = total(current)\n const viewsBefore = total(previous)\n const perDay = Math.round(views / request.days)\n const perDayBefore = Math.round(viewsBefore / request.days)\n const table: PluginFigureTable = {\n title: 'Traffic',\n source,\n period: periodOf(request),\n columns: [\n { key: 'figure', label: 'Figure', kind: 'text' },\n { key: 'current', label: 'This window', kind: 'count' },\n { key: 'previous', label: 'Window before', kind: 'count' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows: [\n { figure: 'Page views', current: views, previous: viewsBefore, change: pluginFigureChange(views, viewsBefore) },\n {\n figure: 'Visitors',\n current: visitors(current),\n previous: visitors(previous),\n change: pluginFigureChange(visitors(current), visitors(previous)),\n },\n {\n figure: 'Page views a day',\n current: perDay,\n previous: perDayBefore,\n change: pluginFigureChange(perDay, perDayBefore),\n },\n ],\n omitted: 0,\n notes: [\n visitorsNote,\n ...(viewsBefore ? [] : ['The window before this one recorded no page views, so there is no change to compare.']),\n ],\n }\n return { ok: true, table }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.pages',\n label: 'Top pages',\n description: `The site's ${AI_TRAFFIC_TOP_PAGES} most viewed pages over the window, with each page's share of all views and its change from the window before.`,\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TOP_PAGES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const now = ranked(sumMaps(current, (day) => day.paths))\n const before = sumMaps(previous, (day) => day.paths)\n const all = now.reduce((sum, [, count]) => sum + count, 0)\n const rows: PluginFigureRow[] = now.slice(0, AI_TRAFFIC_TOP_PAGES).map(([path, views]) => ({\n page: path,\n views,\n share: share(views, all),\n change: pluginFigureChange(views, before.get(path) ?? null),\n }))\n return {\n ok: true,\n table: {\n title: 'Top pages',\n source,\n period: periodOf(request),\n columns: [\n { key: 'page', label: 'Page', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of views', kind: 'percent' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows,\n omitted: Math.max(0, now.length - rows.length),\n notes: [],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.sources',\n label: 'Traffic sources',\n description:\n 'Where visits came from over the window: the referring sites, and the campaign sources and campaigns links were tagged with, with each one’s views.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: SOURCES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const days = await readTrafficDays(db, request.hostId, dayIds(request.now, request.days).current)\n const all = days.reduce((sum, day) => sum + day.total, 0)\n // The collector stores a referring host with its dots as `_`, because a\n // Firestore field path cannot hold one; a host is read back as written.\n const referrers = ranked(sumMaps(days, (day) => day.referrers)).map(\n ([host, views]): [string, number] => [host.replace(/_/g, '.'), views],\n )\n const sources = ranked(sumMaps(days, (day) => day.utm['source'] ?? {}))\n const campaigns = ranked(sumMaps(days, (day) => day.utm['campaign'] ?? {}))\n const rowsOf = (entries: Array<[string, number]>, limit: number, type: string) =>\n entries.slice(0, limit).map(([name, views]) => ({ source: name, type, views, share: share(views, all) }))\n const rows = [\n ...rowsOf(referrers, AI_TRAFFIC_TOP_REFERRERS, 'Referring site'),\n ...rowsOf(sources, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign source'),\n ...rowsOf(campaigns, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign'),\n ]\n return {\n ok: true,\n table: {\n title: 'Traffic sources',\n source,\n period: periodOf(request),\n columns: [\n { key: 'source', label: 'Source', kind: 'text' },\n { key: 'type', label: 'Kind', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of all views', kind: 'percent' },\n ],\n rows,\n omitted:\n Math.max(0, referrers.length - AI_TRAFFIC_TOP_REFERRERS) +\n Math.max(0, sources.length - AI_TRAFFIC_TOP_CAMPAIGNS) +\n Math.max(0, campaigns.length - AI_TRAFFIC_TOP_CAMPAIGNS),\n notes: ['A visit with no referring site, such as a typed address, is in no row.'],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.daily',\n label: 'Traffic by day',\n description: 'Page views and visitors on each day of the window, oldest first, for spotting a day that stood out.',\n windows: AI_TRAFFIC_DAILY_WINDOWS,\n },\n async (db, request) => {\n const ids = [...dayIds(request.now, request.days).current].reverse()\n const days = await readTrafficDays(db, request.hostId, ids)\n return {\n ok: true,\n table: {\n title: 'Traffic by day',\n source,\n period: periodOf(request),\n columns: [\n { key: 'day', label: 'Day', kind: 'date' },\n { key: 'views', label: 'Page views', kind: 'count' },\n { key: 'visitors', label: 'Visitors', kind: 'count' },\n ],\n rows: days.map((day, index) => ({ day: ids[index], views: day.total, visitors: day.visitors })),\n omitted: 0,\n notes: [visitorsNote],\n },\n }\n },\n firestore,\n null,\n ),\n ]\n}\n\n// ── Forms ─────────────────────────────────────────────────────────────────\n\nexport function formsFigureReader(firestore: AiFigureFirestore): PluginFigureReader {\n return siteReader(\n {\n id: 'forms.performance',\n label: 'Forms',\n description:\n 'Each form’s views, submissions, the share of views that became a submission, and leads, over the calendar months the window falls in.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: FORMS_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const { current } = pluginFigureWindows(request.now, request.days)\n const from = formPeriodKey(current.startMs)\n const to = formPeriodKey(current.endMs - 1)\n const snapshot = await db\n .collection('hosts')\n .doc(request.hostId)\n .collection('forms')\n .limit(AI_FORMS_READ_LIMIT)\n .get()\n const forms = snapshot.docs\n .map((doc) => ({ doc, data: (doc.data() ?? {}) as Record<string, unknown> }))\n .filter(({ data }) => !data['deletedAt'])\n .map(({ doc, data }) => {\n const totals = formStatsTotals(data['stats'] as FormStats | undefined, { from, to })\n // Every submission to a form is counted on it, so a form with none\n // recorded in the window had none: 0, not a blank the answer has to\n // hedge over (AGL-3834). Leads are counted only on a form that\n // routes them, so one that does reads 0 the same way, and a form\n // that never has keeps a blank, which the table's note explains.\n const submissions = totals.submissions ?? 0\n const routesLeads = (data['routing'] as { lead?: unknown } | undefined)?.lead === true\n return {\n form: str(data['displayName']) || doc.id,\n views: totals.views,\n submissions,\n completion: totals.views ? share(submissions, totals.views) : null,\n leads: totals.leads ?? (routesLeads ? 0 : null),\n }\n })\n .sort((a, b) => b.submissions - a.submissions || a.form.localeCompare(b.form))\n const monthStart = from ? `${from}-01` : current.from\n return {\n ok: true,\n table: {\n title: 'Forms',\n source: { label: 'Forms', path: 'forms' },\n period: {\n from: monthStart,\n to: current.to,\n days: Math.round((Date.parse(current.to) - Date.parse(monthStart)) / 86_400_000) + 1,\n },\n columns: [\n { key: 'form', label: 'Form', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'submissions', label: 'Submissions', kind: 'count' },\n { key: 'completion', label: 'Views that became a submission', kind: 'percent' },\n { key: 'leads', label: 'Leads', kind: 'count' },\n ],\n rows: forms.slice(0, PLUGIN_FIGURE_MAX_ROWS),\n omitted: Math.max(0, forms.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: [\n 'Form figures are kept by calendar month, so they cover whole months from the first day of the month the window starts in.',\n 'Views are counted in the visitor’s browser and submissions on the server, so a rate can pass 100%.',\n 'A blank Leads figure means the form does not add its submissions to Leads.',\n ],\n },\n }\n },\n firestore,\n 'forms',\n )\n}\n\n/** Every reader this plugin registers, for the platform's own records. */\nexport function aiFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n return [...trafficFigureReaders(firestore), formsFigureReader(firestore)]\n}\n\n/**\n * Registers them from the console surface, the one surface that runs insight\n * jobs. By a call, never by an import (AGL-3025).\n */\nexport function registerAiFigureReaders(firestore: AiFigureFirestore): void {\n for (const reader of aiFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: AI_PLUGIN_ID })\n }\n}\n"],"names":["formPeriodKey","formStatsTotals","PLUGIN_FIGURE_MAX_ROWS","pluginFigureChange","pluginFigureDay","pluginFigureWindows","registerPluginFigureReader","AI_PLUGIN_ID","FORMS_WEEKLY_SUMMARY","SOURCES_WEEKLY_SUMMARY","TOP_PAGES_WEEKLY_SUMMARY","TRAFFIC_WEEKLY_SUMMARY","AI_TRAFFIC_WINDOWS","AI_TRAFFIC_DAILY_WINDOWS","AI_TRAFFIC_TOP_PAGES","AI_TRAFFIC_TOP_REFERRERS","AI_TRAFFIC_TOP_CAMPAIGNS","AI_FORMS_READ_LIMIT","str","value","trim","num","parsed","Number","isFinite","round1","Math","round","share","part","whole","refused","status","error","ok","periodOf","request","current","now","days","from","to","dayIds","previous","walk","startMs","endMs","ids","at","push","Date","counts","out","key","count","Object","entries","n","readTrafficDays","firestore","hostId","length","collection","doc","snapshots","getAll","map","id","snapshot","data","exists","utm","param","values","total","visitors","paths","referrers","sumMaps","pick","totals","Map","day","set","get","ranked","sort","a","b","localeCompare","siteReader","base","read","plugin","scope","windows","includes","trafficFigureReaders","source","label","path","visitorsNote","description","weeklySummary","db","Promise","all","reduce","sum","views","viewsBefore","perDay","perDayBefore","table","title","period","columns","kind","rows","figure","change","omitted","notes","before","slice","page","max","host","replace","sources","campaigns","rowsOf","limit","type","name","reverse","index","formsFigureReader","forms","docs","filter","submissions","routesLeads","lead","form","completion","leads","monthStart","parse","aiFigureReaders","registerAiFigureReaders","reader","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,eAAe,QAAwB,+BAA8B;AAC7F,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,eAAe,EACfC,mBAAmB,EACnBC,0BAA0B,QAMrB,6CAA4C;AACnD,SAASC,YAAY,QAAQ,kBAAc;AAC3C,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,wBAAwB,EACxBC,sBAAsB,QACjB,2BAAuB;AAwB9B,wDAAwD,GACxD,OAAO,MAAMC,qBAAwC;IAAC;IAAG;IAAI;IAAI;CAAG,CAAA;AAEpE,0EAA0E,GAC1E,OAAO,MAAMC,2BAA8C;IAAC;IAAG;CAAG,CAAA;AAElE,kEAAkE,GAClE,OAAO,MAAMC,uBAAuB,GAAE;AAEtC,gFAAgF,GAChF,OAAO,MAAMC,2BAA2B,EAAC;AACzC,OAAO,MAAMC,2BAA2B,EAAC;AAEzC,+BAA+B,GAC/B,OAAO,MAAMC,sBAAsB,IAAG;AAEtC,MAAMC,MAAM,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAEpF,MAAMC,MAAM,CAACF;IACX,MAAMG,SAAS,OAAOH,UAAU,WAAWA,QAAQI,OAAOJ;IAC1D,OAAOI,OAAOC,QAAQ,CAACF,UA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O,SAAS0F,gBAAgB1F,SAA4B;IAC1D,OAAO;WAAIsC,qBAAqBtC;QAAY8E,kBAAkB9E;KAAW;AAC3E;AAEA;;;CAGC,GACD,OAAO,SAAS2F,wBAAwB3F,SAA4B;IAClE,KAAK,MAAM4F,UAAUF,gBAAgB1F,WAAY;QAC/CrD,2BAA2BiJ,QAAQ;YAAEC,UAAUjJ;QAAa;IAC9D;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-readers.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 { formPeriodKey, formStatsTotals, type FormStats } from '@aglyn/aglyn/app-utils/forms'\nimport {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureChange,\n pluginFigureDay,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRead,\n type PluginFigureRequest,\n type PluginFigureRow,\n type PluginFigureTable,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { AI_PLUGIN_ID } from '../constants'\nimport {\n FORMS_WEEKLY_SUMMARY,\n SOURCES_WEEKLY_SUMMARY,\n TOP_PAGES_WEEKLY_SUMMARY,\n TRAFFIC_DAILY_WEEKLY_SUMMARY,\n TRAFFIC_WEEKLY_SUMMARY,\n} from './ai-figure-summaries'\n\n/**\n * The figure readers this plugin registers for records the PLATFORM keeps\n * (AGL-2915): a site's page-view counters and its forms' counters. Every\n * other reader an insight reads is registered by the plugin that owns its\n * records — commerce, bookings, marketing, the workspace's datasets — on the\n * `plugin-figures` seam, and nothing here reads their documents.\n *\n * Each reader answers with one compact table of aggregates, read-only and\n * about nobody: counts, sums and rates, labeled by a page path, a form's name\n * or a referring site — never a visitor or a submission.\n *\n * The readers use the arithmetic their console cards use: the Traffic card's\n * windows and change (`pluginFigureWindows`, `pluginFigureChange`, which are\n * that card's split and delta), and the forms plugin's month counters through\n * `formStatsTotals`, the one function every forms surface windows by.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** How a reader reaches Firestore: resolved when it reads, never when it registers. */\nexport type AiFigureFirestore = () => Firestore\n\n/** The traffic windows: the Traffic card's own ranges. */\nexport const AI_TRAFFIC_WINDOWS: readonly number[] = [7, 14, 30, 90]\n\n/** A day-by-day table fits a table's row bound only over a short window. */\nexport const AI_TRAFFIC_DAILY_WINDOWS: readonly number[] = [7, 14]\n\n/** Pages a pages table lists; the rest are counted in `omitted`. */\nexport const AI_TRAFFIC_TOP_PAGES = 10\n\n/** Referring sites, and campaign sources and campaigns, a sources table lists. */\nexport const AI_TRAFFIC_TOP_REFERRERS = 8\nexport const AI_TRAFFIC_TOP_CAMPAIGNS = 5\n\n/** Forms a forms table reads. */\nexport const AI_FORMS_READ_LIMIT = 100\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nconst num = (value: unknown): number => {\n const parsed = typeof value === 'number' ? value : Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\nconst round1 = (value: number): number => Math.round(value * 10) / 10\n\nconst share = (part: number, whole: number): number | null => (whole > 0 ? round1((part / whole) * 100) : null)\n\nfunction refused(status: 400 | 403 | 404, error: string): PluginFigureRead {\n return { ok: false, status, error }\n}\n\n/** A window's days as the table's period, oldest to newest. */\nfunction periodOf(request: PluginFigureRequest): PluginFigureTable['period'] {\n const { current } = pluginFigureWindows(request.now, request.days)\n return { from: current.from, to: current.to, days: request.days }\n}\n\n/** Every day id of the window and the one before it, newest first. */\nfunction dayIds(now: Date, days: number): { current: string[]; previous: string[] } {\n const { current, previous } = pluginFigureWindows(now, days)\n const walk = (startMs: number, endMs: number): string[] => {\n const ids: string[] = []\n for (let at = endMs - 86_400_000; at >= startMs; at -= 86_400_000) ids.push(pluginFigureDay(new Date(at)))\n return ids\n }\n return { current: walk(current.startMs, current.endMs), previous: walk(previous.startMs, previous.endMs) }\n}\n\n// ── Traffic ───────────────────────────────────────────────────────────────\n\ninterface TrafficDay {\n total: number\n visitors: number\n paths: Record<string, number>\n referrers: Record<string, number>\n utm: Record<string, Record<string, number>>\n}\n\nconst counts = (value: unknown): Record<string, number> => {\n const out: Record<string, number> = {}\n if (!value || typeof value !== 'object') return out\n for (const [key, count] of Object.entries(value as Record<string, unknown>)) {\n const n = num(count)\n if (n > 0) out[key] = n\n }\n return out\n}\n\nasync function readTrafficDays(\n firestore: Firestore,\n hostId: string,\n ids: readonly string[],\n): Promise<TrafficDay[]> {\n if (!ids.length) return []\n const collection = firestore.collection('hosts').doc(hostId).collection('analytics')\n const snapshots = await firestore.getAll(...ids.map((id) => collection.doc(id)))\n return snapshots.map((snapshot) => {\n const data = (snapshot.exists ? snapshot.data() : null) ?? {}\n const utm: Record<string, Record<string, number>> = {}\n for (const [param, values] of Object.entries((data['utm'] ?? {}) as Record<string, unknown>)) {\n utm[param] = counts(values)\n }\n return {\n total: num(data['total']),\n visitors: num(data['visitors']),\n paths: counts(data['paths']),\n referrers: counts(data['referrers']),\n utm,\n }\n })\n}\n\nfunction sumMaps(days: readonly TrafficDay[], pick: (day: TrafficDay) => Record<string, number>): Map<string, number> {\n const totals = new Map<string, number>()\n for (const day of days) {\n for (const [key, count] of Object.entries(pick(day))) totals.set(key, (totals.get(key) ?? 0) + count)\n }\n return totals\n}\n\nconst ranked = (totals: Map<string, number>): Array<[string, number]> =>\n [...totals.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n\nfunction siteReader(\n base: Omit<PluginFigureReader, 'read' | 'scope' | 'plugin'>,\n read: (firestore: Firestore, request: PluginFigureRequest & { hostId: string }) => Promise<PluginFigureRead>,\n firestore: AiFigureFirestore,\n plugin: string | null,\n): PluginFigureReader {\n return {\n ...base,\n scope: 'site',\n plugin,\n read: async (request) => {\n if (!request.hostId) return refused(400, 'Open a site to read its figures')\n if (!base.windows.includes(request.days)) return refused(400, 'That window is not one this reader covers')\n return read(firestore(), { ...request, hostId: request.hostId })\n },\n }\n}\n\nexport function trafficFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n const source = { label: 'Analytics', path: 'analytics' }\n const visitorsNote =\n 'Visitors are counted once per browser tab per day, so one person on two days counts twice.'\n return [\n siteReader(\n {\n id: 'traffic.summary',\n label: 'Traffic',\n description:\n 'Page views, visitors and views a day on the site over the window, each beside the window before it and the change.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TRAFFIC_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const total = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.total, 0)\n const visitors = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.visitors, 0)\n const views = total(current)\n const viewsBefore = total(previous)\n const perDay = Math.round(views / request.days)\n const perDayBefore = Math.round(viewsBefore / request.days)\n const table: PluginFigureTable = {\n title: 'Traffic',\n source,\n period: periodOf(request),\n columns: [\n { key: 'figure', label: 'Figure', kind: 'text' },\n { key: 'current', label: 'This window', kind: 'count' },\n { key: 'previous', label: 'Window before', kind: 'count' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows: [\n { figure: 'Page views', current: views, previous: viewsBefore, change: pluginFigureChange(views, viewsBefore) },\n {\n figure: 'Visitors',\n current: visitors(current),\n previous: visitors(previous),\n change: pluginFigureChange(visitors(current), visitors(previous)),\n },\n {\n figure: 'Page views a day',\n current: perDay,\n previous: perDayBefore,\n change: pluginFigureChange(perDay, perDayBefore),\n },\n ],\n omitted: 0,\n notes: [\n visitorsNote,\n ...(viewsBefore ? [] : ['The window before this one recorded no page views, so there is no change to compare.']),\n ],\n }\n return { ok: true, table }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.pages',\n label: 'Top pages',\n description: `The site's ${AI_TRAFFIC_TOP_PAGES} most viewed pages over the window, with each page's share of all views and its change from the window before.`,\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TOP_PAGES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const now = ranked(sumMaps(current, (day) => day.paths))\n const before = sumMaps(previous, (day) => day.paths)\n const all = now.reduce((sum, [, count]) => sum + count, 0)\n const rows: PluginFigureRow[] = now.slice(0, AI_TRAFFIC_TOP_PAGES).map(([path, views]) => ({\n page: path,\n views,\n share: share(views, all),\n change: pluginFigureChange(views, before.get(path) ?? null),\n }))\n return {\n ok: true,\n table: {\n title: 'Top pages',\n source,\n period: periodOf(request),\n columns: [\n { key: 'page', label: 'Page', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of views', kind: 'percent' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows,\n omitted: Math.max(0, now.length - rows.length),\n notes: [],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.sources',\n label: 'Traffic sources',\n description:\n 'Where visits came from over the window: the referring sites, and the campaign sources and campaigns links were tagged with, with each one’s views.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: SOURCES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const days = await readTrafficDays(db, request.hostId, dayIds(request.now, request.days).current)\n const all = days.reduce((sum, day) => sum + day.total, 0)\n // The collector stores a referring host with its dots as `_`, because a\n // Firestore field path cannot hold one; a host is read back as written.\n const referrers = ranked(sumMaps(days, (day) => day.referrers)).map(\n ([host, views]): [string, number] => [host.replace(/_/g, '.'), views],\n )\n const sources = ranked(sumMaps(days, (day) => day.utm['source'] ?? {}))\n const campaigns = ranked(sumMaps(days, (day) => day.utm['campaign'] ?? {}))\n const rowsOf = (entries: Array<[string, number]>, limit: number, type: string) =>\n entries.slice(0, limit).map(([name, views]) => ({ source: name, type, views, share: share(views, all) }))\n const rows = [\n ...rowsOf(referrers, AI_TRAFFIC_TOP_REFERRERS, 'Referring site'),\n ...rowsOf(sources, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign source'),\n ...rowsOf(campaigns, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign'),\n ]\n return {\n ok: true,\n table: {\n title: 'Traffic sources',\n source,\n period: periodOf(request),\n columns: [\n { key: 'source', label: 'Source', kind: 'text' },\n { key: 'type', label: 'Kind', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of all views', kind: 'percent' },\n ],\n rows,\n omitted:\n Math.max(0, referrers.length - AI_TRAFFIC_TOP_REFERRERS) +\n Math.max(0, sources.length - AI_TRAFFIC_TOP_CAMPAIGNS) +\n Math.max(0, campaigns.length - AI_TRAFFIC_TOP_CAMPAIGNS),\n notes: ['A visit with no referring site, such as a typed address, is in no row.'],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.daily',\n label: 'Traffic by day',\n description: 'Page views and visitors on each day of the window, oldest first, for spotting a day that stood out.',\n windows: AI_TRAFFIC_DAILY_WINDOWS,\n weeklySummary: TRAFFIC_DAILY_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = [...dayIds(request.now, request.days).current].reverse()\n const days = await readTrafficDays(db, request.hostId, ids)\n return {\n ok: true,\n table: {\n title: 'Traffic by day',\n source,\n period: periodOf(request),\n columns: [\n { key: 'day', label: 'Day', kind: 'date' },\n { key: 'views', label: 'Page views', kind: 'count' },\n { key: 'visitors', label: 'Visitors', kind: 'count' },\n ],\n rows: days.map((day, index) => ({ day: ids[index], views: day.total, visitors: day.visitors })),\n omitted: 0,\n notes: [visitorsNote],\n },\n }\n },\n firestore,\n null,\n ),\n ]\n}\n\n// ── Forms ─────────────────────────────────────────────────────────────────\n\nexport function formsFigureReader(firestore: AiFigureFirestore): PluginFigureReader {\n return siteReader(\n {\n id: 'forms.performance',\n label: 'Forms',\n description:\n 'Each form’s views, submissions, the share of views that became a submission, and leads, over the calendar months the window falls in.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: FORMS_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const { current } = pluginFigureWindows(request.now, request.days)\n const from = formPeriodKey(current.startMs)\n const to = formPeriodKey(current.endMs - 1)\n const snapshot = await db\n .collection('hosts')\n .doc(request.hostId)\n .collection('forms')\n .limit(AI_FORMS_READ_LIMIT)\n .get()\n const forms = snapshot.docs\n .map((doc) => ({ doc, data: (doc.data() ?? {}) as Record<string, unknown> }))\n .filter(({ data }) => !data['deletedAt'])\n .map(({ doc, data }) => {\n const totals = formStatsTotals(data['stats'] as FormStats | undefined, { from, to })\n // Every submission to a form is counted on it, so a form with none\n // recorded in the window had none: 0, not a blank the answer has to\n // hedge over (AGL-3834). Leads are counted only on a form that\n // routes them, so one that does reads 0 the same way, and a form\n // that never has keeps a blank, which the table's note explains.\n const submissions = totals.submissions ?? 0\n const routesLeads = (data['routing'] as { lead?: unknown } | undefined)?.lead === true\n return {\n form: str(data['displayName']) || doc.id,\n views: totals.views,\n submissions,\n completion: totals.views ? share(submissions, totals.views) : null,\n leads: totals.leads ?? (routesLeads ? 0 : null),\n }\n })\n .sort((a, b) => b.submissions - a.submissions || a.form.localeCompare(b.form))\n const monthStart = from ? `${from}-01` : current.from\n return {\n ok: true,\n table: {\n title: 'Forms',\n source: { label: 'Forms', path: 'forms' },\n period: {\n from: monthStart,\n to: current.to,\n days: Math.round((Date.parse(current.to) - Date.parse(monthStart)) / 86_400_000) + 1,\n },\n columns: [\n { key: 'form', label: 'Form', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'submissions', label: 'Submissions', kind: 'count' },\n { key: 'completion', label: 'Views that became a submission', kind: 'percent' },\n { key: 'leads', label: 'Leads', kind: 'count' },\n ],\n rows: forms.slice(0, PLUGIN_FIGURE_MAX_ROWS),\n omitted: Math.max(0, forms.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: [\n 'Form figures are kept by calendar month, so they cover whole months from the first day of the month the window starts in.',\n 'Views are counted in the visitor’s browser and submissions on the server, so a rate can pass 100%.',\n 'A blank Leads figure means the form does not add its submissions to Leads.',\n ],\n },\n }\n },\n firestore,\n 'forms',\n )\n}\n\n/** Every reader this plugin registers, for the platform's own records. */\nexport function aiFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n return [...trafficFigureReaders(firestore), formsFigureReader(firestore)]\n}\n\n/**\n * Registers them from the console surface, the one surface that runs insight\n * jobs. By a call, never by an import (AGL-3025).\n */\nexport function registerAiFigureReaders(firestore: AiFigureFirestore): void {\n for (const reader of aiFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: AI_PLUGIN_ID })\n }\n}\n"],"names":["formPeriodKey","formStatsTotals","PLUGIN_FIGURE_MAX_ROWS","pluginFigureChange","pluginFigureDay","pluginFigureWindows","registerPluginFigureReader","AI_PLUGIN_ID","FORMS_WEEKLY_SUMMARY","SOURCES_WEEKLY_SUMMARY","TOP_PAGES_WEEKLY_SUMMARY","TRAFFIC_DAILY_WEEKLY_SUMMARY","TRAFFIC_WEEKLY_SUMMARY","AI_TRAFFIC_WINDOWS","AI_TRAFFIC_DAILY_WINDOWS","AI_TRAFFIC_TOP_PAGES","AI_TRAFFIC_TOP_REFERRERS","AI_TRAFFIC_TOP_CAMPAIGNS","AI_FORMS_READ_LIMIT","str","value","trim","num","parsed","Number","isFinite","round1","Math","round","share","part","whole","refused","status","error","ok","periodOf","request","current","now","days","from","to","dayIds","previous","walk","startMs","endMs","ids","at","push","Date","counts","out","key","count","Object","entries","n","readTrafficDays","firestore","hostId","length","collection","doc","snapshots","getAll","map","id","snapshot","data","exists","utm","param","values","total","visitors","paths","referrers","sumMaps","pick","totals","Map","day","set","get","ranked","sort","a","b","localeCompare","siteReader","base","read","plugin","scope","windows","includes","trafficFigureReaders","source","label","path","visitorsNote","description","weeklySummary","db","Promise","all","reduce","sum","views","viewsBefore","perDay","perDayBefore","table","title","period","columns","kind","rows","figure","change","omitted","notes","before","slice","page","max","host","replace","sources","campaigns","rowsOf","limit","type","name","reverse","index","formsFigureReader","forms","docs","filter","submissions","routesLeads","lead","form","completion","leads","monthStart","parse","aiFigureReaders","registerAiFigureReaders","reader","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,eAAe,QAAwB,+BAA8B;AAC7F,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,eAAe,EACfC,mBAAmB,EACnBC,0BAA0B,QAMrB,6CAA4C;AACnD,SAASC,YAAY,QAAQ,kBAAc;AAC3C,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,wBAAwB,EACxBC,4BAA4B,EAC5BC,sBAAsB,QACjB,2BAAuB;AAwB9B,wDAAwD,GACxD,OAAO,MAAMC,qBAAwC;IAAC;IAAG;IAAI;IAAI;CAAG,CAAA;AAEpE,0EAA0E,GAC1E,OAAO,MAAMC,2BAA8C;IAAC;IAAG;CAAG,CAAA;AAElE,kEAAkE,GAClE,OAAO,MAAMC,uBAAuB,GAAE;AAEtC,gFAAgF,GAChF,OAAO,MAAMC,2BAA2B,EAAC;AACzC,OAAO,MAAMC,2BAA2B,EAAC;AAEzC,+BAA+B,GAC/B,OAAO,MAAMC,sBAAsB,IAAG;AAEtC,MAAMC,MAAM,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAEpF,MAAMC,MAAM,CAACF;IACX,MAAMG,SAAS,OAAOH,UAAU,WAAWA,QAAQI,OAAOJ;IAC1D,OAAOI,OAAOC,QAAQ,CAACF,UAAUA,SAAS;AA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O,SAAS0F,gBAAgB1F,SAA4B;IAC1D,OAAO;WAAIsC,qBAAqBtC;QAAY8E,kBAAkB9E;KAAW;AAC3E;AAEA;;;CAGC,GACD,OAAO,SAAS2F,wBAAwB3F,SAA4B;IAClE,KAAK,MAAM4F,UAAUF,gBAAgB1F,WAAY;QAC/CtD,2BAA2BkJ,QAAQ;YAAEC,UAAUlJ;QAAa;IAC9D;AACF"}
@@ -22,6 +22,7 @@ import type { PluginFigureWeeklySummary } from '@aglyn/aglyn/plugin-manager/plug
22
22
  * the email rather than misreporting.
23
23
  */
24
24
  export declare const TRAFFIC_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
25
+ export declare const TRAFFIC_DAILY_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
25
26
  export declare const TOP_PAGES_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
26
27
  export declare const SOURCES_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
27
28
  export declare const FORMS_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
- import { figureCount, figureHasColumn, figureRanked, figureRow, figureStat, weeklySummaryDay } from "@aglyn/aglyn/app-utils/weekly-summary";
17
+ import { figureBars, figureCount, figureHasColumn, figureRanked, figureRow, figureStat, weeklySummaryDay } from "@aglyn/aglyn/app-utils/weekly-summary";
18
18
  /**
19
19
  * How the traffic and forms readers read in the weekly summary (AGL-3867).
20
20
  * Each answers `null` for a week it has nothing to say about, and for a table
@@ -47,6 +47,16 @@ import { figureCount, figureHasColumn, figureRanked, figureRow, figureStat, week
47
47
  };
48
48
  }
49
49
  };
50
+ export const TRAFFIC_DAILY_WEEKLY_SUMMARY = {
51
+ order: 15,
52
+ summarize: (table)=>{
53
+ const bars = figureHasColumn(table, 'views') ? figureBars(table, 'day', 'views') : [];
54
+ return bars.length ? {
55
+ title: 'Traffic by day',
56
+ bars
57
+ } : null;
58
+ }
59
+ };
50
60
  export const TOP_PAGES_WEEKLY_SUMMARY = {
51
61
  order: 20,
52
62
  summarize: (table)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-summaries.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 type { PluginFigureWeeklySummary } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n figureCount,\n figureHasColumn,\n figureRanked,\n figureRow,\n figureStat,\n weeklySummaryDay,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\n\n/**\n * How the traffic and forms readers read in the weekly summary (AGL-3867).\n * Each answers `null` for a week it has nothing to say about, and for a table\n * that is not the shape it was written for, so a changed reader drops out of\n * the email rather than misreporting.\n */\n\nexport const TRAFFIC_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 10,\n summarize: (table) => {\n const visitors = figureRow(table, 'figure', 'Visitors')\n const views = figureRow(table, 'figure', 'Page views')\n if (!figureCount(visitors?.['current']) && !figureCount(views?.['current'])) return null\n return {\n title: 'Traffic',\n stats: [\n ...(visitors\n ? [figureStat(table, visitors, 'current', 'Visitors', { change: 'change', total: { one: 'visitor', many: 'visitors' } })]\n : []),\n ...(views ? [figureStat(table, views, 'current', 'Page views', { change: 'change' })] : []),\n ],\n }\n },\n}\n\nexport const TOP_PAGES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 20,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'page', 'views') : []\n return rows.length ? { title: 'Top pages', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const SOURCES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 30,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'source', 'views') : []\n return rows.length ? { title: 'Where visits came from', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const FORMS_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 40,\n summarize: (table) => {\n if (!figureHasColumn(table, 'submissions')) return null\n const total = table.rows.reduce((sum, row) => sum + figureCount(row['submissions']), 0)\n if (!total) return null\n // Form figures are kept by calendar month, so the block says so rather\n // than calling a month-to-date count \"last week\".\n const since = table.period ? weeklySummaryDay(table.period.from) : null\n return {\n title: 'Forms',\n stats: [\n {\n label: since ? `Submissions since ${since}` : 'Submissions',\n value: total.toLocaleString('en-US'),\n },\n ],\n rows: figureRanked(table, 'form', 'submissions'),\n }\n },\n}\n"],"names":["figureCount","figureHasColumn","figureRanked","figureRow","figureStat","weeklySummaryDay","TRAFFIC_WEEKLY_SUMMARY","order","summarize","table","visitors","views","title","stats","change","total","one","many","TOP_PAGES_WEEKLY_SUMMARY","rows","length","map","row","value","SOURCES_WEEKLY_SUMMARY","FORMS_WEEKLY_SUMMARY","reduce","sum","since","period","from","label","toLocaleString"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,WAAW,EACXC,eAAe,EACfC,YAAY,EACZC,SAAS,EACTC,UAAU,EACVC,gBAAgB,QACX,wCAAuC;AAE9C;;;;;CAKC,GAED,OAAO,MAAMC,yBAAoD;IAC/DC,OAAO;IACPC,WAAW,CAACC;QACV,MAAMC,WAAWP,UAAUM,OAAO,UAAU;QAC5C,MAAME,QAAQR,UAAUM,OAAO,UAAU;QACzC,IAAI,CAACT,YAAYU,4BAAAA,QAAU,CAAC,UAAU,KAAK,CAACV,YAAYW,yBAA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AuE;QACvE,kDAAkD;QAClD,MAAMa,QAAQnB,MAAMoB,MAAM,GAAGxB,iBAAiBI,MAAMoB,MAAM,CAACC,IAAI,IAAI;QACnE,OAAO;YACLlB,OAAO;YACPC,OAAO;gBACL;oBACEkB,OAAOH,QAAQ,CAAC,kBAAkB,EAAEA,OAAO,GAAG;oBAC9CL,OAAOR,MAAMiB,cAAc,CAAC;gBAC9B;aACD;YACDb,MAAMjB,aAAaO,OAAO,QAAQ;QACpC;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-summaries.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 type { PluginFigureWeeklySummary } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n figureBars,\n figureCount,\n figureHasColumn,\n figureRanked,\n figureRow,\n figureStat,\n weeklySummaryDay,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\n\n/**\n * How the traffic and forms readers read in the weekly summary (AGL-3867).\n * Each answers `null` for a week it has nothing to say about, and for a table\n * that is not the shape it was written for, so a changed reader drops out of\n * the email rather than misreporting.\n */\n\nexport const TRAFFIC_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 10,\n summarize: (table) => {\n const visitors = figureRow(table, 'figure', 'Visitors')\n const views = figureRow(table, 'figure', 'Page views')\n if (!figureCount(visitors?.['current']) && !figureCount(views?.['current'])) return null\n return {\n title: 'Traffic',\n stats: [\n ...(visitors\n ? [figureStat(table, visitors, 'current', 'Visitors', { change: 'change', total: { one: 'visitor', many: 'visitors' } })]\n : []),\n ...(views ? [figureStat(table, views, 'current', 'Page views', { change: 'change' })] : []),\n ],\n }\n },\n}\n\nexport const TRAFFIC_DAILY_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 15,\n summarize: (table) => {\n const bars = figureHasColumn(table, 'views') ? figureBars(table, 'day', 'views') : []\n return bars.length ? { title: 'Traffic by day', bars } : null\n },\n}\n\nexport const TOP_PAGES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 20,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'page', 'views') : []\n return rows.length ? { title: 'Top pages', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const SOURCES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 30,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'source', 'views') : []\n return rows.length ? { title: 'Where visits came from', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const FORMS_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 40,\n summarize: (table) => {\n if (!figureHasColumn(table, 'submissions')) return null\n const total = table.rows.reduce((sum, row) => sum + figureCount(row['submissions']), 0)\n if (!total) return null\n // Form figures are kept by calendar month, so the block says so rather\n // than calling a month-to-date count \"last week\".\n const since = table.period ? weeklySummaryDay(table.period.from) : null\n return {\n title: 'Forms',\n stats: [\n {\n label: since ? `Submissions since ${since}` : 'Submissions',\n value: total.toLocaleString('en-US'),\n },\n ],\n rows: figureRanked(table, 'form', 'submissions'),\n }\n },\n}\n"],"names":["figureBars","figureCount","figureHasColumn","figureRanked","figureRow","figureStat","weeklySummaryDay","TRAFFIC_WEEKLY_SUMMARY","order","summarize","table","visitors","views","title","stats","change","total","one","many","TRAFFIC_DAILY_WEEKLY_SUMMARY","bars","length","TOP_PAGES_WEEKLY_SUMMARY","rows","map","row","value","SOURCES_WEEKLY_SUMMARY","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