@aglyn/plugins-ai 1.32.0 → 1.33.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 +17 -17
- package/src/lib/jobs/ai-job-campaign-step.js +1 -0
- package/src/lib/jobs/ai-job-campaign-step.js.map +1 -1
- package/src/lib/jobs/ai-job-component-step.js +2 -1
- package/src/lib/jobs/ai-job-component-step.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +8 -0
- package/src/lib/jobs/ai-job-drafts.js +18 -12
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/jobs/ai-job-edit-step.d.ts +5 -0
- package/src/lib/jobs/ai-job-edit-step.js +16 -9
- package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
- package/src/lib/jobs/ai-job-email-step.js +1 -0
- package/src/lib/jobs/ai-job-email-step.js.map +1 -1
- package/src/lib/jobs/ai-job-form-step.js +2 -1
- package/src/lib/jobs/ai-job-form-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-step.js +4 -1
- package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
- package/src/lib/jobs/ai-job-navigation-step.js +7 -3
- package/src/lib/jobs/ai-job-navigation-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.js +7 -1
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-privacy-step.d.ts +2 -0
- package/src/lib/jobs/ai-job-privacy-step.js +7 -4
- package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-store-pages.js +3 -1
- package/src/lib/jobs/ai-job-site-store-pages.js.map +1 -1
- package/src/lib/jobs/ai-job-store-links-layout.js +8 -4
- package/src/lib/jobs/ai-job-store-links-layout.js.map +1 -1
- package/src/lib/jobs/ai-job-template-step.js +2 -1
- package/src/lib/jobs/ai-job-template-step.js.map +1 -1
- package/src/lib/jobs/ai-site-import-forms.js +2 -1
- package/src/lib/jobs/ai-site-import-forms.js.map +1 -1
- package/src/lib/jobs/ai-site-import-publish.d.ts +1 -1
- package/src/lib/jobs/ai-site-import-publish.js.map +1 -1
- package/src/lib/jobs/ai-site-late-photos.js +2 -1
- package/src/lib/jobs/ai-site-late-photos.js.map +1 -1
- package/src/lib/jobs/ai-site-publish.d.ts +2 -2
- package/src/lib/jobs/ai-site-publish.js +23 -15
- package/src/lib/jobs/ai-site-publish.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame-source.js +1 -0
- package/src/lib/layout-language/ai-layout-frame-source.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.js +7 -0
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/server/ai-experiment-versions.js +6 -3
- package/src/lib/server/ai-experiment-versions.js.map +1 -1
- package/src/lib/server/ai-page-content.js +2 -1
- package/src/lib/server/ai-page-content.js.map +1 -1
- package/src/lib/server/ai-seo-apply.js +6 -3
- package/src/lib/server/ai-seo-apply.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-template-step.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 { throwIfAiJobCanceled } from './ai-job-cancel'\nimport { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport { normalizeScreenSlug } from '@aglyn/aglyn/app-utils/screen-route'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n AI_TEMPLATE_SUBJECTS,\n aiBindingTokensIn,\n aiTemplateAddressTokens,\n isAiAddressToken,\n isAiUnreadToken,\n parseAiTemplateJobInputs,\n type AiTemplateSubjectDefinition,\n} from '../model/ai-template-subjects'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n aiDoctrineTreeTool,\n runValidatedGeneration,\n type AiValidatedTree,\n} from '../runtime/ai-doctrine'\nimport {\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiTemplateExamplesSystemBlock } from '../runtime/ai-template-examples'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport { aiLayoutMotionSiteOf } from './ai-job-page-language'\nimport { aiWithSiteMotion } from '../layout-language/ai-layout-motion'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiTemplateDraftNodes,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiConfirmedPlan,\n aiCopySourceLines,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlacedComponentIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiPlanReuseViolations,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport { aiPlannedTemplateTokens, aiPlanTemplateTokenViolations } from './ai-job-plan-conformance'\nimport {\n aiBuildingPlanCreations,\n aiJobPlanCreationsRefusal,\n aiPlanCreationsRunMinimumMs,\n} from './ai-job-plan-creations'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The template step (AGL-2909): the generation step of a `template` job, run\n * once a member confirmed the job's plan.\n *\n * It builds ONE page template — the page a site renders once per record: a\n * content collection's entry, a product, an author — through\n * `runValidatedGeneration('template', …)`. Everything that differs per\n * record is a binding token from the subject's vocabulary\n * (`model/ai-template-subjects.ts`), which is the list the besigner's insert\n * picker offers for that page; a link or media prop may hold one of those\n * tokens whole, which the palette validator admits only because this door\n * names them. The door adds one check of its own through `extend` (rule 8):\n * no token the page does not fill, an h1 bound to the subject's title, no\n * block that fills itself only on another subject's page, and no address,\n * slug or timestamp printed in its copy.\n *\n * The model is shown the platform's starter pages as examples, in a cached\n * block (`runtime/ai-template-examples.ts`), and writes against them.\n *\n * The template lands in the site's library as a new draft\n * (`ai-job-drafts.ts`), inert until a member uses it: bound to no\n * collection, set as no product or author page, served nowhere. A plan that\n * starts from a copy of a template the site has gets that copy instead.\n */\n\n/** The longest answer a template may run to; the tree is held to the template budget either way. */\nexport const AI_JOB_TEMPLATE_MAX_TOKENS = AI_ROUTING_TABLE['job.template'].maxTokens\n\n/**\n * The template step's time (AGL-3035, AGL-3036): its two inventory-lookup\n * rounds, its answer and its re-ask at the routing table's ceiling on the tier\n * `job.template` is served from, fitted to what a beat can give a step. It\n * runs on the job beat, never at an inline door, and asks for no more of the\n * ceiling than fits that time on the model it runs.\n */\nexport const AI_JOB_TEMPLATE_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.template'],\n maxTokens: AI_JOB_TEMPLATE_MAX_TOKENS,\n})\n\n/** The least time one template step needs before it starts. */\nexport const AI_JOB_TEMPLATE_STEP_MINIMUM_MS = AI_JOB_TEMPLATE_STEP_BUDGET.minimumMs\n\n/** The template step's own instructions, cached after the doctrine and before the examples. */\nexport const AI_JOB_TEMPLATE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one page template: the page a website renders once for each record it keeps, such as each entry of a content collection, each product or each author. Answer with submit_template: the whole page as one flat node map.',\n 'Everything that differs from one record to the next is a binding token, never typed copy. The request names what the page is for, the tokens that page fills and the blocks that fill themselves there; bind only those tokens.',\n 'The page’s one h1 holds the title token the request names. Copy that reads the same on every record, such as a section heading, is written in the site’s voice.',\n 'A link or media prop holds exactly one token from the request’s link and media tokens, such as an Image whose src is {{entry.coverImage}}; its alt text may combine words and tokens. Copy never prints a link or media token, a slug or a timestamp.',\n 'A template carries no third-party player. It plays a video token only when the confirmed plan lists it, in a Video (video) whose src is that token and whose poster is the cover image token.',\n 'The page renders inside the site’s layout, so it carries no header, navigation or footer of its own.',\n ].join('\\n'),\n },\n]\n\n/** A content collection an entry template is for, as the prompt and the draft name it. */\nexport interface AiTemplateCollection {\n id: string\n name: string\n slug: string\n}\n\n/** The content collection by that id on the site, or `null` when there is none. */\nexport async function readAiTemplateCollection(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n collectionId: string,\n): Promise<AiTemplateCollection | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .doc(collectionId)\n .get()\n if (!snapshot.exists) return null\n const data = (snapshot.data() ?? {}) as Record<string, unknown>\n if (hostCollectionKind(data) !== 'content') return null\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n const slug = text(data['slug'])\n return {\n id: collectionId,\n name: text(data['displayName']) || text(data['name']) || slug || collectionId,\n slug,\n }\n}\n\n/** The template's name: the plan's, else the collection's or the subject's. */\nexport function aiTemplateDraftName(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n planned: string | null | undefined,\n): string {\n return planned || (collection ? `${collection.name} entry template` : definition.defaultName)\n}\n\n/** The address Use template offers for the page it creates. */\nexport function aiTemplateDraftSlug(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n): string | null {\n return (\n normalizeScreenSlug(\n collection\n ? `${collection.slug || collection.id}-entry-template`\n : `${definition.subject}-page-template`,\n ) ?? null\n )\n}\n\n/** The template job as the generation's user turn, with the template a short copy would have started from (AGL-3143 §14). */\nexport function aiJobTemplatePrompt(\n job: Pick<AiJob, 'brief'>,\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n plan: AiJobPlan | null,\n name: string,\n source: readonly string[] = [],\n): string {\n const of = collection\n ? ` of the \"${collection.name}\" collection${collection.slug ? ` (/${collection.slug})` : ''}`\n : ''\n return [\n `Template name: ${name}`,\n `The page is for ${definition.noun}${of}.`,\n `Title token: ${definition.titleToken}`,\n `Tokens this page fills: ${definition.tokens.map((entry) => `${entry.token} ${entry.label}`).join('; ')}`,\n `Link and media tokens: ${aiTemplateAddressTokens(definition).join(', ')}`,\n definition.blocks.length\n ? `Blocks that fill themselves on this page: ${definition.blocks.join(', ')}`\n : 'No block fills itself on this page: bind the tokens.',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ...source,\n ].join('\\n')\n}\n\n/** Which subject's page each self-filling block belongs to. */\nconst BLOCK_SUBJECTS = new Map<string, AiTemplateSubjectDefinition>(\n AI_TEMPLATE_SUBJECTS.flatMap((subject) =>\n AI_TEMPLATE_SUBJECT_DEFINITIONS[subject].blocks.map(\n (block) => [block, AI_TEMPLATE_SUBJECT_DEFINITIONS[subject]] as const,\n ),\n ),\n)\n\n/** Every string a prop value holds, however deeply. */\nfunction stringsIn(value: unknown, out: string[] = []): string[] {\n if (typeof value === 'string') out.push(value)\n else if (Array.isArray(value)) for (const inner of value) stringsIn(inner, out)\n else if (value && typeof value === 'object') {\n for (const inner of Object.values(value as Record<string, unknown>)) stringsIn(inner, out)\n }\n return out\n}\n\n/** The page's title: a Typography that renders as an h1. */\nfunction isPageTitle(node: AiDoctrineNode): boolean {\n if (node.componentId !== 'muiTypography') return false\n const element = typeof node.props?.['component'] === 'string' ? String(node.props['component']) : ''\n return (element || String(node.props?.['variant'] ?? '')) === 'h1'\n}\n\n/**\n * The tokens a prop prints for a reader that no reader reads: a link or\n * picture token, a slug or a timestamp, in copy (AGL-3143 §16). Copy is a\n * prop the palette gives the text role, read as words where it holds more\n * than one token or is the element's children. A block handed one token\n * whole reads it as a value, as Entry Meta's avatar takes the author's\n * portrait and a Video's publication date takes the timestamp, and a\n * markdown link's target is followed, not read.\n */\nfunction printedTokens(node: AiDoctrineNode): string[] {\n const roles = AI_PALETTE[node.componentId]?.propRoles ?? {}\n return Object.entries(node.props ?? {}).flatMap(([key, value]) => {\n if (typeof value !== 'string' || roles[key] !== 'text') return []\n const tokens = aiBindingTokensIn(value.replace(/\\]\\([^)]*\\)/g, ']'))\n const unread = tokens.filter((token) => isAiAddressToken(token) || isAiUnreadToken(token))\n const whole = tokens.length === 1 && value.trim() === tokens[0]\n return unread.length && (key === 'children' || !whole) ? unread : []\n })\n}\n\n/**\n * The template door's check on a tree the doctrine admitted (rule 8): every\n * token is one the page fills, the h1 binds the subject's title, no block\n * that fills itself on another subject's page is placed — except inside a\n * Collection Entries card, where each fills from the card's own entry — and\n * no copy prints an address, a slug or a timestamp.\n */\nexport function aiTemplateBindingCheck(\n definition: AiTemplateSubjectDefinition,\n): (tree: AiValidatedTree) => AiDoctrineViolation[] {\n const allowed = new Set(definition.tokens.map((entry) => entry.token))\n return (tree) => {\n const nodes = tree.nodes as unknown as Record<string, AiDoctrineNode>\n const unknown = new Set<string>()\n const unknownAt: string[] = []\n const foreign: Array<{ id: string; componentId: string; owner: AiTemplateSubjectDefinition }> = []\n const titles: string[] = []\n const printed = new Set<string>()\n const printedAt: string[] = []\n let titleBound = false\n for (const { id, node, ancestors } of walkTree({ rootId: tree.rootId, nodes })) {\n const tokens = stringsIn(node.props).flatMap(aiBindingTokensIn)\n const strays = tokens.filter((token) => !allowed.has(token))\n if (strays.length) {\n for (const token of strays) unknown.add(token)\n unknownAt.push(id)\n }\n const shown = printedTokens(node).filter((token) => allowed.has(token))\n if (shown.length) {\n for (const token of shown) printed.add(token)\n printedAt.push(id)\n }\n const owner = BLOCK_SUBJECTS.get(node.componentId)\n const inCard = ancestors.some((ancestor) => nodes[ancestor]?.componentId === 'collectionEntries')\n if (owner && owner.subject !== definition.subject && !inCard) {\n foreign.push({ id, componentId: node.componentId, owner })\n }\n if (isPageTitle(node)) {\n titles.push(id)\n if (tokens.includes(definition.titleToken)) titleBound = true\n }\n }\n const violations: AiDoctrineViolation[] = []\n if (unknown.size) {\n violations.push({\n rule: 8,\n code: 'unknown-binding',\n message: `This binds ${[...unknown].slice(0, 3).join(', ')}, which ${definition.noun}’s page does not fill. Bind only the tokens listed for this page.`,\n nodeIds: aiModelNodeIds(unknownAt, tree.sourceIds),\n })\n }\n if (printed.size) {\n violations.push({\n rule: 8,\n code: 'printed-token',\n message: `This prints ${[...printed].slice(0, 3).join(', ')} in the page's copy, where a reader sees an address, a slug or a timestamp. A link or picture token goes whole in a link or media prop, and a slug or a timestamp stays off the page.`,\n nodeIds: aiModelNodeIds(printedAt, tree.sourceIds),\n })\n }\n // The doctrine already refuses a page with no h1 or with several.\n if (titles.length === 1 && !titleBound) {\n violations.push({\n rule: 8,\n code: 'typed-title',\n message: `The page title is typed, so every record would show the same one. Put ${definition.titleToken} in the h1.`,\n nodeIds: aiModelNodeIds(titles, tree.sourceIds),\n })\n }\n if (foreign.length) {\n const [first] = foreign\n violations.push({\n rule: 8,\n code: 'foreign-block',\n message: `The ${AI_PALETTE[first.componentId]?.displayName ?? first.componentId} block fills itself only on ${first.owner.noun}’s page, and this template is for ${definition.noun}. Remove it.`,\n nodeIds: aiModelNodeIds(\n foreign.map((entry) => entry.id),\n tree.sourceIds,\n ),\n })\n }\n return violations\n }\n}\n\nexport interface AiTemplateJobAdmissionDeps {\n readCollection?: typeof readAiTemplateCollection\n}\n\n/**\n * A template job is admitted with inputs that say what the page is for, for\n * a site of the job's own org that holds the collection it names, with a\n * template to spare.\n */\nexport function createAiTemplateJobAdmission(deps: AiTemplateJobAdmissionDeps = {}): AiJobAdmission {\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n return async (context) => {\n const inputs = parseAiTemplateJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n return aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'template',\n org: context.org,\n ownCheck: async (hostId) =>\n inputs.collectionId && !(await readCollection(context.firestore, hostId, inputs.collectionId))\n ? { status: 404, error: 'That content collection is not on this site' }\n : aiJobPlanCreationsRefusal('template', context, hostId),\n })\n }\n}\n\nexport interface AiJobTemplateStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n readCollection?: typeof readAiTemplateCollection\n /** The starter examples block; built from the starters once per process otherwise. */\n examples?: () => AiSystemBlock\n}\n\n/**\n * The binding tokens the confirmed plan gives the template, against the\n * template a COPY actually produced (AGL-3024); `null` when the copy keeps\n * the plan, or when the plan promised no token to keep.\n *\n * The same hole as `aiCopiedLayoutReview` and `aiCopiedPageReview`, on the\n * third kind that can start from a duplicate. The generate path already holds\n * a built template to `aiPlanTemplateTokenViolations`; the copy path reached\n * none of it, so a plan reading \"duplicate it and bind the author's photo\"\n * got the duplicate and reported Done.\n *\n * A copy that cannot be read back settles nothing, and a promise this step\n * cannot settle is reviewed by a person rather than reported as kept.\n */\nexport async function aiCopiedTemplateReview(\n firestore: FirebaseFirestore.Firestore,\n input: {\n hostId: string\n id: string\n name: string\n plan: AiJobPlan | null\n definition: AiTemplateSubjectDefinition\n },\n): Promise<AiJobReview | null> {\n const { tokens, unreadable } = aiPlannedTemplateTokens(input.plan, input.definition)\n if (!tokens.length && !unreadable.length) return null\n const stored = await readAiTemplateDraftNodes(firestore, {\n hostId: input.hostId,\n id: input.id,\n })\n const nodes = (stored ?? {}) as unknown as Record<string, AiDoctrineNode>\n if (!nodes[CANVAS_ROOT_ELEMENT_ID]) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the template the plan names, and this job could not read the copy back to check it shows what the plan gives it. Open the template and check it before you apply it.`,\n findings: [],\n }\n }\n const violations = aiPlanTemplateTokenViolations(input.plan, input.definition, {\n rootId: CANVAS_ROOT_ELEMENT_ID,\n nodes,\n })\n if (!violations.length) return null\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the template the plan names, and a copy is all it is: ${violations[0].message}`,\n violations,\n })\n}\n\nexport function createAiJobTemplateStep(deps: AiJobTemplateStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n const examples = deps.examples ?? aiTemplateExamplesSystemBlock\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a template job names no site, and its admission refuses one')\n const inputs = parseAiTemplateJobInputs(job.inputs)\n if (typeof inputs === 'string') {\n throw new Error(`a template job's inputs no longer read as they were admitted: ${inputs}`)\n }\n const definition = AI_TEMPLATE_SUBJECT_DEFINITIONS[inputs.subject]\n const output = (draft: AiDraftRecord, load?: AiLoadEstimate | null): AiJobOutput => ({\n resource: 'template',\n id: draft.id,\n versionId: null,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.template') ?? aiModelForStep('job.template')\n\n // A run cut off after its draft was written reports that draft, found by the id the job recorded.\n const draftId = aiJobDraftId(job, 'template')\n const written = await readAiDraft(firestore, { kind: 'template', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot, collection] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n inputs.collectionId\n ? readCollection(firestore, hostId, inputs.collectionId)\n : Promise.resolve(null),\n ])\n if (inputs.collectionId && !collection) {\n throw new Error(`collection ${inputs.collectionId} left site ${hostId} after its template job was admitted`)\n }\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'template')\n const name = aiTemplateDraftName(definition, collection, creation?.name)\n\n // The plan starts from a copy of a template the site has (rule 15): the\n // copy is the draft, and nothing is generated. A source gone since the\n // plan was made is built from the brief instead, and one that cannot keep\n // the plan's tokens is built FROM (AGL-3143 §14): copying it could only end\n // in the review below. A source this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.templates.find((template) => template.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedTemplateReview(firestore, { hostId, id: source.id, name: source.name, plan, definition })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n const sourceLines =\n source && sourceShort\n ? aiCopySourceLines(\n 'template',\n source.name,\n (await readAiTemplateDraftNodes(firestore, { hostId, id: source.id })) as Record<string, unknown> | null,\n )\n : []\n if (creation?.duplicateOf && source && !sourceShort) {\n const copy = await duplicate('template', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // The copy is reported with what the plan promised of it read back\n // (AGL-3024): this branch generates nothing, so nothing else can.\n const review = await aiCopiedTemplateReview(firestore, {\n hostId,\n id: copy.id,\n name: copy.name,\n plan,\n definition,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: null, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'template', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n const result = await runValidatedGeneration('template', {\n step: 'job.template',\n model,\n instructions: [...AI_JOB_TEMPLATE_INSTRUCTIONS, examples()],\n inventory,\n messages: [\n {\n role: 'user',\n content: aiJobTemplatePrompt(job, definition, collection, plan, name, sourceLines),\n },\n ],\n tool: aiDoctrineTreeTool('template'),\n maxTokens: AI_JOB_TEMPLATE_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.template'].thinking ? { thinking: AI_ROUTING_TABLE['job.template'].thinking } : {}),\n ...(AI_ROUTING_TABLE['job.template'].effort ? { effort: AI_ROUTING_TABLE['job.template'].effort } : {}),\n context: { bindingTokens: aiTemplateAddressTokens(definition) },\n // Rule 8's binding check, and the confirmed plan kept in both halves: a\n // token the plan promised that the template does not bind (AGL-3143\n // §11), and a component the plan reuses that it does not place. The\n // layout and component doors hold their builds to that reuse; the\n // template door did not, so it could drop a promised component and\n // still answer `Done` (AGL-3024).\n extend: (tree) => [\n ...aiTemplateBindingCheck(definition)(tree),\n ...aiPlanTemplateTokenViolations(plan, definition, {\n rootId: tree.rootId,\n nodes: tree.nodes as unknown as Record<string, AiDoctrineNode>,\n }),\n ...aiPlanReuseViolations(inventory, plan, aiPlacedComponentIds(tree), 'template'),\n ],\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'template',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n // The site's entrance motion, as its pages have (AGL-3838): a post or a\n // record opens the way the rest of the site does.\n nodes: aiWithSiteMotion(result.value.nodes, aiLayoutMotionSiteOf(job, ''), { rootId: result.value.rootId }),\n slug: aiTemplateDraftSlug(definition, collection),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its template was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n return { ...spent, outputs: [output(draft, result.value.load)] }\n }\n}\n\n/** The template step, building the components and forms its plan creates before the template (AGL-3143 §15). */\nexport const runAiJobTemplateStep = aiBuildingPlanCreations('template', 'job.template', createAiJobTemplateStep())\n\n/** Registers the template step and the check a template job passes before it is created or resumed. */\nexport function registerAiTemplateJob(): void {\n registerAiJobStep('template', runAiJobTemplateStep, {\n minimumMs: AI_JOB_TEMPLATE_STEP_MINIMUM_MS,\n minimumMsFor: aiPlanCreationsRunMinimumMs('template'),\n })\n registerAiJobAdmission('template', createAiTemplateJobAdmission())\n}\n"],"names":["throwIfAiJobCanceled","hostCollectionKind","normalizeScreenSlug","duplicateResource","CANVAS_ROOT_ELEMENT_ID","AI_TEMPLATE_SUBJECT_DEFINITIONS","AI_TEMPLATE_SUBJECTS","aiBindingTokensIn","aiTemplateAddressTokens","isAiAddressToken","isAiUnreadToken","parseAiTemplateJobInputs","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","walkTree","AI_PALETTE","aiTemplateExamplesSystemBlock","readSiteInventory","registerAiJobAdmission","aiJobDraftId","aiLayoutMotionSiteOf","aiWithSiteMotion","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiTemplateDraftNodes","writeAiDraft","aiConfirmedPlan","aiCopySourceLines","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlacedComponentIds","aiPlanCreation","aiPlanReferenceLines","aiPlanReuseViolations","aiUnspentOutcome","aiPlannedTemplateTokens","aiPlanTemplateTokenViolations","aiBuildingPlanCreations","aiJobPlanCreationsRefusal","aiPlanCreationsRunMinimumMs","aiJobStepBudget","registerAiJobStep","AI_JOB_TEMPLATE_MAX_TOKENS","maxTokens","AI_JOB_TEMPLATE_STEP_BUDGET","tier","AI_JOB_TEMPLATE_STEP_MINIMUM_MS","minimumMs","AI_JOB_TEMPLATE_INSTRUCTIONS","text","join","readAiTemplateCollection","firestore","hostId","collectionId","snapshot","collection","doc","get","exists","data","value","trim","slug","id","name","aiTemplateDraftName","definition","planned","defaultName","aiTemplateDraftSlug","subject","aiJobTemplatePrompt","job","plan","source","of","noun","titleToken","tokens","map","entry","token","label","blocks","length","BLOCK_SUBJECTS","Map","flatMap","block","stringsIn","out","push","Array","isArray","inner","Object","values","isPageTitle","node","componentId","element","props","String","printedTokens","roles","propRoles","entries","key","replace","unread","filter","whole","aiTemplateBindingCheck","allowed","Set","tree","nodes","unknown","unknownAt","foreign","titles","printed","printedAt","titleBound","ancestors","rootId","strays","has","add","shown","owner","inCard","some","ancestor","includes","violations","size","rule","code","message","slice","nodeIds","sourceIds","first","displayName","createAiTemplateJobAdmission","deps","readCollection","context","inputs","status","error","orgId","kind","org","ownCheck","aiCopiedTemplateReview","input","unreadable","stored","reason","findings","createAiJobTemplateStep","readInventory","duplicate","examples","now","signal","modelFor","orgSnapshot","Error","output","draft","load","resource","versionId","hostSubdomain","model","draftId","written","outputs","inventory","Promise","all","resolve","creation","duplicateOf","templates","find","template","undefined","sourceReview","sourceShort","Boolean","sourceLines","copy","sourceId","uid","createdBy","attemptKey","ok","review","allowance","result","step","instructions","messages","role","content","tool","thinking","effort","bindingTokens","extend","spent","refused","runAiJobTemplateStep","registerAiTemplateJob","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AACtD,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,mBAAmB,QAAQ,sCAAqC;AAEzE,SAASC,iB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2C,uBAAuBpL,wBAAwB,YAAY,gBAAgB8H,2BAA0B;AAElH,qGAAqG,GACrG,OAAO,SAASuD;IACdjL,kBAAkB,YAAYgL,sBAAsB;QAClD1K,WAAWD;QACX6K,cAAcpL,4BAA4B;IAC5C;IACA1B,uBAAuB,YAAYqI;AACrC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-template-step.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 { throwIfAiJobCanceled } from './ai-job-cancel'\nimport { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport { normalizeScreenSlug } from '@aglyn/aglyn/app-utils/screen-route'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n AI_TEMPLATE_SUBJECTS,\n aiBindingTokensIn,\n aiTemplateAddressTokens,\n isAiAddressToken,\n isAiUnreadToken,\n parseAiTemplateJobInputs,\n type AiTemplateSubjectDefinition,\n} from '../model/ai-template-subjects'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n aiDoctrineTreeTool,\n runValidatedGeneration,\n type AiValidatedTree,\n} from '../runtime/ai-doctrine'\nimport {\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiTemplateExamplesSystemBlock } from '../runtime/ai-template-examples'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport { aiLayoutMotionSiteOf } from './ai-job-page-language'\nimport { aiWithSiteMotion } from '../layout-language/ai-layout-motion'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiTemplateDraftNodes,\n aiJobContentActor,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiConfirmedPlan,\n aiCopySourceLines,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlacedComponentIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiPlanReuseViolations,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport { aiPlannedTemplateTokens, aiPlanTemplateTokenViolations } from './ai-job-plan-conformance'\nimport {\n aiBuildingPlanCreations,\n aiJobPlanCreationsRefusal,\n aiPlanCreationsRunMinimumMs,\n} from './ai-job-plan-creations'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The template step (AGL-2909): the generation step of a `template` job, run\n * once a member confirmed the job's plan.\n *\n * It builds ONE page template — the page a site renders once per record: a\n * content collection's entry, a product, an author — through\n * `runValidatedGeneration('template', …)`. Everything that differs per\n * record is a binding token from the subject's vocabulary\n * (`model/ai-template-subjects.ts`), which is the list the besigner's insert\n * picker offers for that page; a link or media prop may hold one of those\n * tokens whole, which the palette validator admits only because this door\n * names them. The door adds one check of its own through `extend` (rule 8):\n * no token the page does not fill, an h1 bound to the subject's title, no\n * block that fills itself only on another subject's page, and no address,\n * slug or timestamp printed in its copy.\n *\n * The model is shown the platform's starter pages as examples, in a cached\n * block (`runtime/ai-template-examples.ts`), and writes against them.\n *\n * The template lands in the site's library as a new draft\n * (`ai-job-drafts.ts`), inert until a member uses it: bound to no\n * collection, set as no product or author page, served nowhere. A plan that\n * starts from a copy of a template the site has gets that copy instead.\n */\n\n/** The longest answer a template may run to; the tree is held to the template budget either way. */\nexport const AI_JOB_TEMPLATE_MAX_TOKENS = AI_ROUTING_TABLE['job.template'].maxTokens\n\n/**\n * The template step's time (AGL-3035, AGL-3036): its two inventory-lookup\n * rounds, its answer and its re-ask at the routing table's ceiling on the tier\n * `job.template` is served from, fitted to what a beat can give a step. It\n * runs on the job beat, never at an inline door, and asks for no more of the\n * ceiling than fits that time on the model it runs.\n */\nexport const AI_JOB_TEMPLATE_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.template'],\n maxTokens: AI_JOB_TEMPLATE_MAX_TOKENS,\n})\n\n/** The least time one template step needs before it starts. */\nexport const AI_JOB_TEMPLATE_STEP_MINIMUM_MS = AI_JOB_TEMPLATE_STEP_BUDGET.minimumMs\n\n/** The template step's own instructions, cached after the doctrine and before the examples. */\nexport const AI_JOB_TEMPLATE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one page template: the page a website renders once for each record it keeps, such as each entry of a content collection, each product or each author. Answer with submit_template: the whole page as one flat node map.',\n 'Everything that differs from one record to the next is a binding token, never typed copy. The request names what the page is for, the tokens that page fills and the blocks that fill themselves there; bind only those tokens.',\n 'The page’s one h1 holds the title token the request names. Copy that reads the same on every record, such as a section heading, is written in the site’s voice.',\n 'A link or media prop holds exactly one token from the request’s link and media tokens, such as an Image whose src is {{entry.coverImage}}; its alt text may combine words and tokens. Copy never prints a link or media token, a slug or a timestamp.',\n 'A template carries no third-party player. It plays a video token only when the confirmed plan lists it, in a Video (video) whose src is that token and whose poster is the cover image token.',\n 'The page renders inside the site’s layout, so it carries no header, navigation or footer of its own.',\n ].join('\\n'),\n },\n]\n\n/** A content collection an entry template is for, as the prompt and the draft name it. */\nexport interface AiTemplateCollection {\n id: string\n name: string\n slug: string\n}\n\n/** The content collection by that id on the site, or `null` when there is none. */\nexport async function readAiTemplateCollection(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n collectionId: string,\n): Promise<AiTemplateCollection | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .doc(collectionId)\n .get()\n if (!snapshot.exists) return null\n const data = (snapshot.data() ?? {}) as Record<string, unknown>\n if (hostCollectionKind(data) !== 'content') return null\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n const slug = text(data['slug'])\n return {\n id: collectionId,\n name: text(data['displayName']) || text(data['name']) || slug || collectionId,\n slug,\n }\n}\n\n/** The template's name: the plan's, else the collection's or the subject's. */\nexport function aiTemplateDraftName(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n planned: string | null | undefined,\n): string {\n return planned || (collection ? `${collection.name} entry template` : definition.defaultName)\n}\n\n/** The address Use template offers for the page it creates. */\nexport function aiTemplateDraftSlug(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n): string | null {\n return (\n normalizeScreenSlug(\n collection\n ? `${collection.slug || collection.id}-entry-template`\n : `${definition.subject}-page-template`,\n ) ?? null\n )\n}\n\n/** The template job as the generation's user turn, with the template a short copy would have started from (AGL-3143 §14). */\nexport function aiJobTemplatePrompt(\n job: Pick<AiJob, 'brief'>,\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n plan: AiJobPlan | null,\n name: string,\n source: readonly string[] = [],\n): string {\n const of = collection\n ? ` of the \"${collection.name}\" collection${collection.slug ? ` (/${collection.slug})` : ''}`\n : ''\n return [\n `Template name: ${name}`,\n `The page is for ${definition.noun}${of}.`,\n `Title token: ${definition.titleToken}`,\n `Tokens this page fills: ${definition.tokens.map((entry) => `${entry.token} ${entry.label}`).join('; ')}`,\n `Link and media tokens: ${aiTemplateAddressTokens(definition).join(', ')}`,\n definition.blocks.length\n ? `Blocks that fill themselves on this page: ${definition.blocks.join(', ')}`\n : 'No block fills itself on this page: bind the tokens.',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ...source,\n ].join('\\n')\n}\n\n/** Which subject's page each self-filling block belongs to. */\nconst BLOCK_SUBJECTS = new Map<string, AiTemplateSubjectDefinition>(\n AI_TEMPLATE_SUBJECTS.flatMap((subject) =>\n AI_TEMPLATE_SUBJECT_DEFINITIONS[subject].blocks.map(\n (block) => [block, AI_TEMPLATE_SUBJECT_DEFINITIONS[subject]] as const,\n ),\n ),\n)\n\n/** Every string a prop value holds, however deeply. */\nfunction stringsIn(value: unknown, out: string[] = []): string[] {\n if (typeof value === 'string') out.push(value)\n else if (Array.isArray(value)) for (const inner of value) stringsIn(inner, out)\n else if (value && typeof value === 'object') {\n for (const inner of Object.values(value as Record<string, unknown>)) stringsIn(inner, out)\n }\n return out\n}\n\n/** The page's title: a Typography that renders as an h1. */\nfunction isPageTitle(node: AiDoctrineNode): boolean {\n if (node.componentId !== 'muiTypography') return false\n const element = typeof node.props?.['component'] === 'string' ? String(node.props['component']) : ''\n return (element || String(node.props?.['variant'] ?? '')) === 'h1'\n}\n\n/**\n * The tokens a prop prints for a reader that no reader reads: a link or\n * picture token, a slug or a timestamp, in copy (AGL-3143 §16). Copy is a\n * prop the palette gives the text role, read as words where it holds more\n * than one token or is the element's children. A block handed one token\n * whole reads it as a value, as Entry Meta's avatar takes the author's\n * portrait and a Video's publication date takes the timestamp, and a\n * markdown link's target is followed, not read.\n */\nfunction printedTokens(node: AiDoctrineNode): string[] {\n const roles = AI_PALETTE[node.componentId]?.propRoles ?? {}\n return Object.entries(node.props ?? {}).flatMap(([key, value]) => {\n if (typeof value !== 'string' || roles[key] !== 'text') return []\n const tokens = aiBindingTokensIn(value.replace(/\\]\\([^)]*\\)/g, ']'))\n const unread = tokens.filter((token) => isAiAddressToken(token) || isAiUnreadToken(token))\n const whole = tokens.length === 1 && value.trim() === tokens[0]\n return unread.length && (key === 'children' || !whole) ? unread : []\n })\n}\n\n/**\n * The template door's check on a tree the doctrine admitted (rule 8): every\n * token is one the page fills, the h1 binds the subject's title, no block\n * that fills itself on another subject's page is placed — except inside a\n * Collection Entries card, where each fills from the card's own entry — and\n * no copy prints an address, a slug or a timestamp.\n */\nexport function aiTemplateBindingCheck(\n definition: AiTemplateSubjectDefinition,\n): (tree: AiValidatedTree) => AiDoctrineViolation[] {\n const allowed = new Set(definition.tokens.map((entry) => entry.token))\n return (tree) => {\n const nodes = tree.nodes as unknown as Record<string, AiDoctrineNode>\n const unknown = new Set<string>()\n const unknownAt: string[] = []\n const foreign: Array<{ id: string; componentId: string; owner: AiTemplateSubjectDefinition }> = []\n const titles: string[] = []\n const printed = new Set<string>()\n const printedAt: string[] = []\n let titleBound = false\n for (const { id, node, ancestors } of walkTree({ rootId: tree.rootId, nodes })) {\n const tokens = stringsIn(node.props).flatMap(aiBindingTokensIn)\n const strays = tokens.filter((token) => !allowed.has(token))\n if (strays.length) {\n for (const token of strays) unknown.add(token)\n unknownAt.push(id)\n }\n const shown = printedTokens(node).filter((token) => allowed.has(token))\n if (shown.length) {\n for (const token of shown) printed.add(token)\n printedAt.push(id)\n }\n const owner = BLOCK_SUBJECTS.get(node.componentId)\n const inCard = ancestors.some((ancestor) => nodes[ancestor]?.componentId === 'collectionEntries')\n if (owner && owner.subject !== definition.subject && !inCard) {\n foreign.push({ id, componentId: node.componentId, owner })\n }\n if (isPageTitle(node)) {\n titles.push(id)\n if (tokens.includes(definition.titleToken)) titleBound = true\n }\n }\n const violations: AiDoctrineViolation[] = []\n if (unknown.size) {\n violations.push({\n rule: 8,\n code: 'unknown-binding',\n message: `This binds ${[...unknown].slice(0, 3).join(', ')}, which ${definition.noun}’s page does not fill. Bind only the tokens listed for this page.`,\n nodeIds: aiModelNodeIds(unknownAt, tree.sourceIds),\n })\n }\n if (printed.size) {\n violations.push({\n rule: 8,\n code: 'printed-token',\n message: `This prints ${[...printed].slice(0, 3).join(', ')} in the page's copy, where a reader sees an address, a slug or a timestamp. A link or picture token goes whole in a link or media prop, and a slug or a timestamp stays off the page.`,\n nodeIds: aiModelNodeIds(printedAt, tree.sourceIds),\n })\n }\n // The doctrine already refuses a page with no h1 or with several.\n if (titles.length === 1 && !titleBound) {\n violations.push({\n rule: 8,\n code: 'typed-title',\n message: `The page title is typed, so every record would show the same one. Put ${definition.titleToken} in the h1.`,\n nodeIds: aiModelNodeIds(titles, tree.sourceIds),\n })\n }\n if (foreign.length) {\n const [first] = foreign\n violations.push({\n rule: 8,\n code: 'foreign-block',\n message: `The ${AI_PALETTE[first.componentId]?.displayName ?? first.componentId} block fills itself only on ${first.owner.noun}’s page, and this template is for ${definition.noun}. Remove it.`,\n nodeIds: aiModelNodeIds(\n foreign.map((entry) => entry.id),\n tree.sourceIds,\n ),\n })\n }\n return violations\n }\n}\n\nexport interface AiTemplateJobAdmissionDeps {\n readCollection?: typeof readAiTemplateCollection\n}\n\n/**\n * A template job is admitted with inputs that say what the page is for, for\n * a site of the job's own org that holds the collection it names, with a\n * template to spare.\n */\nexport function createAiTemplateJobAdmission(deps: AiTemplateJobAdmissionDeps = {}): AiJobAdmission {\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n return async (context) => {\n const inputs = parseAiTemplateJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n return aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'template',\n org: context.org,\n ownCheck: async (hostId) =>\n inputs.collectionId && !(await readCollection(context.firestore, hostId, inputs.collectionId))\n ? { status: 404, error: 'That content collection is not on this site' }\n : aiJobPlanCreationsRefusal('template', context, hostId),\n })\n }\n}\n\nexport interface AiJobTemplateStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n readCollection?: typeof readAiTemplateCollection\n /** The starter examples block; built from the starters once per process otherwise. */\n examples?: () => AiSystemBlock\n}\n\n/**\n * The binding tokens the confirmed plan gives the template, against the\n * template a COPY actually produced (AGL-3024); `null` when the copy keeps\n * the plan, or when the plan promised no token to keep.\n *\n * The same hole as `aiCopiedLayoutReview` and `aiCopiedPageReview`, on the\n * third kind that can start from a duplicate. The generate path already holds\n * a built template to `aiPlanTemplateTokenViolations`; the copy path reached\n * none of it, so a plan reading \"duplicate it and bind the author's photo\"\n * got the duplicate and reported Done.\n *\n * A copy that cannot be read back settles nothing, and a promise this step\n * cannot settle is reviewed by a person rather than reported as kept.\n */\nexport async function aiCopiedTemplateReview(\n firestore: FirebaseFirestore.Firestore,\n input: {\n hostId: string\n id: string\n name: string\n plan: AiJobPlan | null\n definition: AiTemplateSubjectDefinition\n },\n): Promise<AiJobReview | null> {\n const { tokens, unreadable } = aiPlannedTemplateTokens(input.plan, input.definition)\n if (!tokens.length && !unreadable.length) return null\n const stored = await readAiTemplateDraftNodes(firestore, {\n hostId: input.hostId,\n id: input.id,\n })\n const nodes = (stored ?? {}) as unknown as Record<string, AiDoctrineNode>\n if (!nodes[CANVAS_ROOT_ELEMENT_ID]) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the template the plan names, and this job could not read the copy back to check it shows what the plan gives it. Open the template and check it before you apply it.`,\n findings: [],\n }\n }\n const violations = aiPlanTemplateTokenViolations(input.plan, input.definition, {\n rootId: CANVAS_ROOT_ELEMENT_ID,\n nodes,\n })\n if (!violations.length) return null\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the template the plan names, and a copy is all it is: ${violations[0].message}`,\n violations,\n })\n}\n\nexport function createAiJobTemplateStep(deps: AiJobTemplateStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n const examples = deps.examples ?? aiTemplateExamplesSystemBlock\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a template job names no site, and its admission refuses one')\n const inputs = parseAiTemplateJobInputs(job.inputs)\n if (typeof inputs === 'string') {\n throw new Error(`a template job's inputs no longer read as they were admitted: ${inputs}`)\n }\n const definition = AI_TEMPLATE_SUBJECT_DEFINITIONS[inputs.subject]\n const output = (draft: AiDraftRecord, load?: AiLoadEstimate | null): AiJobOutput => ({\n resource: 'template',\n id: draft.id,\n versionId: null,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.template') ?? aiModelForStep('job.template')\n\n // A run cut off after its draft was written reports that draft, found by the id the job recorded.\n const draftId = aiJobDraftId(job, 'template')\n const written = await readAiDraft(firestore, { kind: 'template', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot, collection] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n inputs.collectionId\n ? readCollection(firestore, hostId, inputs.collectionId)\n : Promise.resolve(null),\n ])\n if (inputs.collectionId && !collection) {\n throw new Error(`collection ${inputs.collectionId} left site ${hostId} after its template job was admitted`)\n }\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'template')\n const name = aiTemplateDraftName(definition, collection, creation?.name)\n\n // The plan starts from a copy of a template the site has (rule 15): the\n // copy is the draft, and nothing is generated. A source gone since the\n // plan was made is built from the brief instead, and one that cannot keep\n // the plan's tokens is built FROM (AGL-3143 §14): copying it could only end\n // in the review below. A source this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.templates.find((template) => template.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedTemplateReview(firestore, { hostId, id: source.id, name: source.name, plan, definition })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n const sourceLines =\n source && sourceShort\n ? aiCopySourceLines(\n 'template',\n source.name,\n (await readAiTemplateDraftNodes(firestore, { hostId, id: source.id })) as Record<string, unknown> | null,\n )\n : []\n if (creation?.duplicateOf && source && !sourceShort) {\n const copy = await duplicate('template', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // The copy is reported with what the plan promised of it read back\n // (AGL-3024): this branch generates nothing, so nothing else can.\n const review = await aiCopiedTemplateReview(firestore, {\n hostId,\n id: copy.id,\n name: copy.name,\n plan,\n definition,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: null, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'template', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n const result = await runValidatedGeneration('template', {\n step: 'job.template',\n model,\n instructions: [...AI_JOB_TEMPLATE_INSTRUCTIONS, examples()],\n inventory,\n messages: [\n {\n role: 'user',\n content: aiJobTemplatePrompt(job, definition, collection, plan, name, sourceLines),\n },\n ],\n tool: aiDoctrineTreeTool('template'),\n maxTokens: AI_JOB_TEMPLATE_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.template'].thinking ? { thinking: AI_ROUTING_TABLE['job.template'].thinking } : {}),\n ...(AI_ROUTING_TABLE['job.template'].effort ? { effort: AI_ROUTING_TABLE['job.template'].effort } : {}),\n context: { bindingTokens: aiTemplateAddressTokens(definition) },\n // Rule 8's binding check, and the confirmed plan kept in both halves: a\n // token the plan promised that the template does not bind (AGL-3143\n // §11), and a component the plan reuses that it does not place. The\n // layout and component doors hold their builds to that reuse; the\n // template door did not, so it could drop a promised component and\n // still answer `Done` (AGL-3024).\n extend: (tree) => [\n ...aiTemplateBindingCheck(definition)(tree),\n ...aiPlanTemplateTokenViolations(plan, definition, {\n rootId: tree.rootId,\n nodes: tree.nodes as unknown as Record<string, AiDoctrineNode>,\n }),\n ...aiPlanReuseViolations(inventory, plan, aiPlacedComponentIds(tree), 'template'),\n ],\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'template',\n hostId,\n id: draftId,\n uid: job.createdBy,\n actor: aiJobContentActor(job),\n org,\n name,\n // The site's entrance motion, as its pages have (AGL-3838): a post or a\n // record opens the way the rest of the site does.\n nodes: aiWithSiteMotion(result.value.nodes, aiLayoutMotionSiteOf(job, ''), { rootId: result.value.rootId }),\n slug: aiTemplateDraftSlug(definition, collection),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its template was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n return { ...spent, outputs: [output(draft, result.value.load)] }\n }\n}\n\n/** The template step, building the components and forms its plan creates before the template (AGL-3143 §15). */\nexport const runAiJobTemplateStep = aiBuildingPlanCreations('template', 'job.template', createAiJobTemplateStep())\n\n/** Registers the template step and the check a template job passes before it is created or resumed. */\nexport function registerAiTemplateJob(): void {\n registerAiJobStep('template', runAiJobTemplateStep, {\n minimumMs: AI_JOB_TEMPLATE_STEP_MINIMUM_MS,\n minimumMsFor: aiPlanCreationsRunMinimumMs('template'),\n })\n registerAiJobAdmission('template', createAiTemplateJobAdmission())\n}\n"],"names":["throwIfAiJobCanceled","hostCollectionKind","normalizeScreenSlug","duplicateResource","CANVAS_ROOT_ELEMENT_ID","AI_TEMPLATE_SUBJECT_DEFINITIONS","AI_TEMPLATE_SUBJECTS","aiBindingTokensIn","aiTemplateAddressTokens","isAiAddressToken","isAiUnreadToken","parseAiTemplateJobInputs","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","walkTree","AI_PALETTE","aiTemplateExamplesSystemBlock","readSiteInventory","registerAiJobAdmission","aiJobDraftId","aiLayoutMotionSiteOf","aiWithSiteMotion","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiTemplateDraftNodes","aiJobContentActor","writeAiDraft","aiConfirmedPlan","aiCopySourceLines","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlacedComponentIds","aiPlanCreation","aiPlanReferenceLines","aiPlanReuseViolations","aiUnspentOutcome","aiPlannedTemplateTokens","aiPlanTemplateTokenViolations","aiBuildingPlanCreations","aiJobPlanCreationsRefusal","aiPlanCreationsRunMinimumMs","aiJobStepBudget","registerAiJobStep","AI_JOB_TEMPLATE_MAX_TOKENS","maxTokens","AI_JOB_TEMPLATE_STEP_BUDGET","tier","AI_JOB_TEMPLATE_STEP_MINIMUM_MS","minimumMs","AI_JOB_TEMPLATE_INSTRUCTIONS","text","join","readAiTemplateCollection","firestore","hostId","collectionId","snapshot","collection","doc","get","exists","data","value","trim","slug","id","name","aiTemplateDraftName","definition","planned","defaultName","aiTemplateDraftSlug","subject","aiJobTemplatePrompt","job","plan","source","of","noun","titleToken","tokens","map","entry","token","label","blocks","length","BLOCK_SUBJECTS","Map","flatMap","block","stringsIn","out","push","Array","isArray","inner","Object","values","isPageTitle","node","componentId","element","props","String","printedTokens","roles","propRoles","entries","key","replace","unread","filter","whole","aiTemplateBindingCheck","allowed","Set","tree","nodes","unknown","unknownAt","foreign","titles","printed","printedAt","titleBound","ancestors","rootId","strays","has","add","shown","owner","inCard","some","ancestor","includes","violations","size","rule","code","message","slice","nodeIds","sourceIds","first","displayName","createAiTemplateJobAdmission","deps","readCollection","context","inputs","status","error","orgId","kind","org","ownCheck","aiCopiedTemplateReview","input","unreadable","stored","reason","findings","createAiJobTemplateStep","readInventory","duplicate","examples","now","signal","modelFor","orgSnapshot","Error","output","draft","load","resource","versionId","hostSubdomain","model","draftId","written","outputs","inventory","Promise","all","resolve","creation","duplicateOf","templates","find","template","undefined","sourceReview","sourceShort","Boolean","sourceLines","copy","sourceId","uid","createdBy","attemptKey","ok","review","allowance","result","step","instructions","messages","role","content","tool","thinking","effort","bindingTokens","extend","spent","refused","actor","runAiJobTemplateStep","registerAiTemplateJob","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AACtD,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,mBAAmB,QAAQ,sCAAqC;AAEzE,SAASC,iBAAiB,QAAQ,qDAAoD;AACtF,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SACEC,+BAA+B,EAC/BC,oBAAoB,EACpBC,iBAAiB,EACjBC,uBAAuB,EACvBC,gBAAgB,EAChBC,eAAe,EACfC,wBAAwB,QAEnB,mCAA+B;AACtC,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SACEC,kBAAkB,EAClBC,sBAAsB,QAEjB,4BAAwB;AAC/B,SACEC,QAAQ,QAGH,uCAAmC;AAE1C,SAASC,UAAU,QAAQ,qCAAiC;AAE5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,MAAM,KAAK,WAAW,OAAO,aAAKgE;YAAOC,SAAS;;QAC7D,IAAIZ,OAAOrD,MAAM,KAAK,eAAe,OAAO,aAAKgE;YAAOb,QAAQjL,iBAAiBmL;;QAEjF,qDAAqD;QACrDrN,qBAAqBiL;QACrB,MAAMK,QAAQ,MAAMvJ,aAAa8B,WAAW;YAC1CsG,MAAM;YACNrG;YACAW,IAAImH;YACJmB,KAAK7H,IAAI8H,SAAS;YAClBkB,OAAOpM,kBAAkBoD;YACzBkF;YACA1F;YACA,wEAAwE;YACxE,kDAAkD;YAClDoD,OAAOtG,iBAAiB6L,OAAO/I,KAAK,CAACwD,KAAK,EAAEvG,qBAAqB2D,KAAK,KAAK;gBAAEqD,QAAQ8E,OAAO/I,KAAK,CAACiE,MAAM;YAAC;YACzG/D,MAAMO,oBAAoBH,YAAYX;YACtC+G;QACF;QACA,IAAIM,MAAM4B,EAAE,KAAK,OAAO;YACtB,IAAI5B,MAAMtB,MAAM,KAAK,KAAK,MAAM,IAAIoB,MAAM,CAAC,KAAK,EAAEtH,OAAO,0CAA0C,CAAC;YACpG,OAAO,aAAKkK;gBAAOb,QAAQ9K,cAAciJ,MAAMrB,KAAK;;QACtD;QACA,OAAO,aAAK+D;YAAOlC,SAAS;gBAACT,OAAOC,OAAO+B,OAAO/I,KAAK,CAACiH,IAAI;aAAE;;IAChE;AACF;AAEA,8GAA8G,GAC9G,OAAO,MAAM4C,uBAAuBrL,wBAAwB,YAAY,gBAAgB8H,2BAA0B;AAElH,qGAAqG,GACrG,OAAO,SAASwD;IACdlL,kBAAkB,YAAYiL,sBAAsB;QAClD3K,WAAWD;QACX8K,cAAcrL,4BAA4B;IAC5C;IACA3B,uBAAuB,YAAYsI;AACrC"}
|
|
@@ -36,7 +36,7 @@ import { NodeType } from "@aglyn/aglyn/types/nodes";
|
|
|
36
36
|
import { AI_PALETTE } from "../runtime/ai-palette.generated.js";
|
|
37
37
|
import { readSiteInventory } from "../runtime/site-inventory.js";
|
|
38
38
|
import { aiFormDraft, aiFormDraftViolations } from "./ai-job-form-step.js";
|
|
39
|
-
import { writeAiDraft } from "./ai-job-drafts.js";
|
|
39
|
+
import { aiJobContentActor, writeAiDraft } from "./ai-job-drafts.js";
|
|
40
40
|
/** What a rebuilt form is called where no heading stands above it. */ export const AI_SITE_IMPORT_FORM_DEFAULT_NAME = 'Contact form';
|
|
41
41
|
/** The node a rebuilt form hangs from. */ const FORM_NODE_ID = 'importedForm';
|
|
42
42
|
/** Customer-safe sentences, on the page's row. */ export const AI_SITE_IMPORT_FORM_COPY = {
|
|
@@ -315,6 +315,7 @@ const sameFields = (a, b)=>{
|
|
|
315
315
|
hostId,
|
|
316
316
|
id: formId,
|
|
317
317
|
uid: job.createdBy,
|
|
318
|
+
actor: aiJobContentActor(job),
|
|
318
319
|
org,
|
|
319
320
|
name,
|
|
320
321
|
nodes: draft.nodes,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-forms.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * A FORM ON A PAGE BROUGHT IN, REBUILT AS THE SITE'S OWN (AGL-4083).\n *\n * A fresh site has no saved form, so an import that placed only a form the\n * site already had left \"Send us a message\" with nothing under it. A form on\n * a page brought in is rebuilt from its fields, by code and with no model:\n * the same fields, required marks and button, built of MUI's separate form\n * elements as the Forms page builds them, and saved as a form draft of the\n * site, as a form job saves one (`aiFormDraft`, `writeAiDraft`). Its answers\n * land in the site's Inbox, and the consent field every form that asks for an\n * email carries takes the place of the source's own marketing box. A form\n * with a password or a card field never gets here: the reader leaves it out.\n *\n * A site that already has this form places it. A site with no room for\n * another keeps the page's words and is told why. The form's id comes from\n * the job and the form's fields, so a pass run twice writes one form.\n *=========================================*/\n\nimport { createHash } from 'node:crypto'\nimport { FORM_COMPONENT_ID, FORM_DISPLAY_NAME_MAX_LENGTH, FORM_INPUT_ELEMENT_IDS, isMarketingConsentFieldName } from '@aglyn/aglyn/app-utils/forms'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport type { AiJob, AiJobItemLedger, AiJobOutput } from '../model/ai-jobs.types'\nimport type { AiSiteImportPage, AiSiteImportState, SiteImportLayout, SiteImportLayoutNode } from '../model/ai-site-import'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport type { SiteImportBlock, SiteImportForm, SiteImportFormField } from '../site-import/site-import-html'\nimport { aiFormDraft, aiFormDraftViolations } from './ai-job-form-step'\nimport { writeAiDraft } from './ai-job-drafts'\n\n/** What a rebuilt form is called where no heading stands above it. */\nexport const AI_SITE_IMPORT_FORM_DEFAULT_NAME = 'Contact form'\n\n/** The node a rebuilt form hangs from. */\nconst FORM_NODE_ID = 'importedForm'\n\n/** Customer-safe sentences, on the page's row. */\nexport const AI_SITE_IMPORT_FORM_COPY = {\n rebuilt: (name: string) => `Your form “${name}” is rebuilt on this page, and what visitors send lands in your Inbox.`,\n noRoom: 'Your plan has no room for another form, so this page’s form is left out. Every word of the page is here.',\n notBuilt: 'This page’s form could not be rebuilt, so it is left out. Every word of the page is here.',\n leftOut: (fields: readonly string[]) => `A form can’t take a file here, so “${fields.join('”, “')}” is left out of it.`,\n} as const\n\nconst clean = (text: string | undefined) => (text ?? '').replace(/\\s+/g, ' ').trim()\n\n/** A field's words in camelCase, for a name a form can submit under. */\nfunction camelCase(words: string): string {\n const parts = words.match(/[A-Za-z0-9]+/g) ?? []\n return parts.map((part, at) => (at === 0 ? part.toLowerCase() : `${part[0]?.toUpperCase()}${part.slice(1).toLowerCase()}`)).join('')\n}\n\n/** The name a field submits under: the source's where it reads as one, else its words'. Never a second of one name. */\nfunction fieldNameOf(field: SiteImportFormField, at: number, taken: Set<string>): string {\n const own = /^[A-Za-z][A-Za-z0-9_-]{0,62}$/.test(field.name) ? field.name : ''\n const base = own || camelCase(field.label ?? '') || `field${at + 1}`\n let name = base\n for (let next = 2; taken.has(name.toLowerCase()); next += 1) name = `${base}${next}`\n taken.add(name.toLowerCase())\n return name\n}\n\n/**\n * A form of a page brought in as a tree of the Form element and MUI's separate\n * form elements: each field a Form Control holding its Form Label and its\n * answer, a lone tick a Choice Label holding one Checkbox, as the Forms page\n * builds them. The tree `aiFormDraft` stamps, binds and declares.\n */\nexport function aiSiteImportFormTree(form: SiteImportForm): { rootId: string; nodes: NodesMap } {\n const { formControl, formLabel, input, select, selectOption, radioGroup, radio, checkbox, choiceLabel, datePicker, timePicker } = FORM_INPUT_ELEMENT_IDS\n const nodes: NodesMap = {}\n const add = (id: string, componentId: string, parentId: string, props: Record<string, unknown>, children: readonly string[] = []) => {\n nodes[id] = { $id: id, type: NodeType.NODE, componentId, pluginId: AI_PALETTE[componentId]?.pluginId, parentId, nodes: [...children], props } as NodesMap[string]\n return id\n }\n const taken = new Set<string>()\n const children = form.fields.map((field, at) => {\n const id = `field${at}`\n const name = fieldNameOf(field, at, taken)\n const label = clean(field.label) || name\n const required = field.required ? { required: true } : {}\n const placeholder = field.placeholder ? { placeholder: field.placeholder } : {}\n const options = (field.options ?? []).map(clean).filter(Boolean)\n const choice = (index: number, words: string, element: string, props: Record<string, unknown>, parent: string) => {\n const box = add(`${id}-opt-${index}-input`, element, `${id}-opt-${index}`, props)\n return add(`${id}-opt-${index}`, choiceLabel, parent, { label: words }, [box])\n }\n // A lone tick is its own question: the words beside it say it all.\n if (field.type === 'checkbox' && options.length <= 1) return choice(0, options[0] ?? label, checkbox, { name, value: options[0] ?? label, ...required }, FORM_NODE_ID)\n const wrapper = (answers: readonly string[]) => add(id, formControl, FORM_NODE_ID, { fullWidth: true, ...required }, [add(`${id}-label`, formLabel, id, { children: label }), ...answers])\n if (field.type === 'checkbox') return wrapper(options.map((option, index) => choice(index, option, checkbox, { name, value: option }, id)))\n if (field.type === 'radio' && options.length) {\n const group = add(`${id}-input`, radioGroup, id, { name }, options.map((option, index) => choice(index, option, radio, { value: option, ...required }, `${id}-input`)))\n return wrapper([group])\n }\n if (field.type === 'select' && options.length) {\n const list = add(`${id}-input`, select, id, { name, fullWidth: true, ...required, ...placeholder }, options.map((option, index) => add(`${id}-opt-${index}`, selectOption, `${id}-input`, { children: option })))\n return wrapper([list])\n }\n if (field.type === 'date' || field.type === 'time') return wrapper([add(`${id}-input`, field.type === 'date' ? datePicker : timePicker, id, { name, ...required })])\n const type = ['email', 'tel', 'url', 'number'].includes(field.type) ? field.type : 'text'\n return wrapper([add(`${id}-input`, input, id, { name, type, ...(field.type === 'textarea' ? { multiline: true, minRows: 3 } : {}), ...placeholder, ...required, fullWidth: true })])\n })\n const submit = clean(form.submit)\n nodes[FORM_NODE_ID] = { $id: FORM_NODE_ID, type: NodeType.NODE, componentId: FORM_COMPONENT_ID, pluginId: AI_PALETTE[FORM_COMPONENT_ID]?.pluginId, nodes: children, props: submit ? { submitLabel: submit } : {} } as NodesMap[string]\n return { rootId: FORM_NODE_ID, nodes }\n}\n\n/** What identifies a form across a site's pages: what it asks and its button, never where it sits. */\nexport function aiSiteImportFormSignature(form: SiteImportForm): string {\n const shape = form.fields.map((field) => [field.type, field.name, clean(field.label), field.required === true, field.options ?? []])\n return createHash('sha256').update(JSON.stringify([shape, clean(form.submit)])).digest('hex').slice(0, 12)\n}\n\n/** Each form of a page's layout, with the nearest heading above it in its section: what it is called. */\nexport function aiSiteImportFormPlaces(layout: SiteImportLayout, blocks: readonly SiteImportBlock[]): Array<{ form: number; heading: string | null }> {\n const places: Array<{ form: number; heading: string | null }> = []\n let heading: string | null = null\n const note = (ref: number) => {\n const block = blocks[ref]\n if (block?.kind === 'heading') heading = clean(block.text) || heading\n }\n const visit = (nodes: readonly SiteImportLayoutNode[]) => {\n for (const node of nodes) {\n if (node.kind === 'line') note(node.line)\n else if (node.kind === 'form') places.push({ form: node.form, heading })\n else if (node.kind === 'row') for (const cell of node.cells) visit(cell.nodes)\n else if (node.kind === 'group') for (const item of node.items) item.lines.forEach(note)\n else if (node.kind === 'tabs') for (const tab of node.tabs) visit(tab.panel)\n }\n }\n for (const section of layout.sections) {\n heading = null\n visit(section.nodes)\n }\n return places\n}\n\n/** The forms of a page still to rebuild or place: each one of its layout that asks something. */\nexport function aiSiteImportFormsOwed(page: Pick<AiSiteImportPage, 'read'>): Array<{ form: number; heading: string | null }> {\n const { read } = page\n if (!read?.layout || !read.forms?.length) return []\n return aiSiteImportFormPlaces(read.layout, read.blocks ?? []).filter((place) => (read.forms?.[place.form]?.fields.length ?? 0) > 0)\n}\n\nconst askedNames = (names: readonly string[]) => names.filter((name) => !isMarketingConsentFieldName(name)).map((name) => name.toLowerCase()).sort()\n\nconst sameFields = (a: readonly string[], b: readonly string[]) => {\n const [one, two] = [askedNames(a), askedNames(b)]\n return one.length === two.length && one.every((name, at) => name === two[at])\n}\n\nexport interface AiSiteImportFormsDeps {\n readInventory?: typeof readSiteInventory\n writeDraft?: typeof writeAiDraft\n}\n\nexport interface AiSiteImportFormsRebuilt {\n /** Each form of the page by its index on the read, and the saved form that takes its place; `null` where none does. */\n forms: Array<{ index: number; formId: string | null }>\n /** A ledger row for each form written, at no credits. */\n rows: AiJobItemLedger[]\n outputs: AiJobOutput[]\n /** What the page's row says of its forms. */\n note: string | null\n}\n\n/**\n * A page's forms as the site's own: one the site already has is placed, and\n * any other is saved as a form of the site (AGL-4083). Pure of any model, so\n * it spends nothing; a site with no room keeps the page's words and is told.\n */\nexport async function aiRebuildImportedForms(\n firestore: FirebaseFirestore.Firestore,\n input: { job: Pick<AiJob, '$id' | 'orgId' | 'createdBy'>; hostId: string; state: AiSiteImportState; page: AiSiteImportPage; org: Partial<AglynOrgBilling> | null; now: Date },\n deps: AiSiteImportFormsDeps = {},\n): Promise<AiSiteImportFormsRebuilt> {\n const { job, hostId, state, page, org, now } = input\n const write = deps.writeDraft ?? writeAiDraft\n const inventory = await (deps.readInventory ?? readSiteInventory)(job.orgId, hostId, { firestore })\n const saved = (inventory?.forms ?? []).map((form) => ({ id: form.id, fields: form.fields ?? [] }))\n let met = state.pages.some((entry) => entry.forms?.length)\n const out: AiSiteImportFormsRebuilt = { forms: [], rows: [], outputs: [], note: null }\n const notes: string[] = []\n for (const place of aiSiteImportFormsOwed(page)) {\n const form = page.read?.forms?.[place.form] as SiteImportForm\n const signature = aiSiteImportFormSignature(form)\n const formId = `${job.$id}-form-${signature}`\n const name = (place.heading ?? '').slice(0, FORM_DISPLAY_NAME_MAX_LENGTH) || AI_SITE_IMPORT_FORM_DEFAULT_NAME\n const draft = aiFormDraft(aiSiteImportFormTree(form), { routing: { kind: 'inbox', list: null }, cannotCollect: [] }, { formId, name })\n const names = draft.fields.map((field) => field.fieldName)\n // A site's only form takes the first form an import meets, as it always has.\n const existing = saved.find((entry) => entry.id === formId || sameFields(entry.fields, names)) ?? (!met && saved.length === 1 ? saved[0] : undefined)\n met = true\n if (existing) {\n out.forms.push({ index: place.form, formId: existing.id })\n continue\n }\n if (aiFormDraftViolations(draft, formId, {}).length) {\n out.forms.push({ index: place.form, formId: null })\n notes.push(AI_SITE_IMPORT_FORM_COPY.notBuilt)\n continue\n }\n const written = await write(firestore, {\n kind: 'form',\n hostId,\n id: formId,\n uid: job.createdBy,\n org,\n name,\n nodes: draft.nodes,\n form: { rootId: draft.rootId, formNodeId: draft.formNodeId, fields: draft.fields, consentFieldName: draft.consentFieldName, routing: draft.routing },\n now,\n })\n if (written.ok === false) {\n if (written.status === 404) throw new Error(`site ${hostId} vanished while its form was rebuilt`)\n out.forms.push({ index: place.form, formId: null })\n notes.push(AI_SITE_IMPORT_FORM_COPY.noRoom)\n continue\n }\n saved.push({ id: formId, fields: names })\n out.forms.push({ index: place.form, formId })\n notes.push(AI_SITE_IMPORT_FORM_COPY.rebuilt(written.name))\n if (form.leftOut?.length) notes.push(AI_SITE_IMPORT_FORM_COPY.leftOut(form.leftOut))\n out.rows.push({ slot: `form-${signature}`, op: 'form', label: written.name, status: 'succeeded', attempt: 1, creditsSpent: 0, creditsRefunded: 0, outputs: [formId] })\n out.outputs.push({ resource: 'form', id: formId, versionId: written.versionId, hostId, hostSubdomain: written.hostSubdomain, label: written.name })\n }\n out.note = [...new Set(notes)].join(' ') || null\n return out\n}\n"],"names":["createHash","FORM_COMPONENT_ID","FORM_DISPLAY_NAME_MAX_LENGTH","FORM_INPUT_ELEMENT_IDS","isMarketingConsentFieldName","NodeType","AI_PALETTE","readSiteInventory","aiFormDraft","aiFormDraftViolations","writeAiDraft","AI_SITE_IMPORT_FORM_DEFAULT_NAME","FORM_NODE_ID","AI_SITE_IMPORT_FORM_COPY","rebuilt","name","noRoom","notBuilt","leftOut","fields","join","clean","text","replace","trim","camelCase","words","parts","match","map","part","at","toLowerCase","toUpperCase","slice","fieldNameOf","field","taken","own","test","base","label","next","has","add","aiSiteImportFormTree","form","formControl","formLabel","input","select","selectOption","radioGroup","radio","checkbox","choiceLabel","datePicker","timePicker","nodes","id","componentId","parentId","props","children","$id","type","NODE","pluginId","Set","options","required","placeholder","filter","Boolean","choice","index","element","parent","box","length","value","wrapper","answers","fullWidth","option","group","list","includes","multiline","minRows","submit","submitLabel","rootId","aiSiteImportFormSignature","shape","update","JSON","stringify","digest","aiSiteImportFormPlaces","layout","blocks","places","heading","note","ref","block","kind","visit","node","line","push","cell","cells","item","items","lines","forEach","tab","tabs","panel","section","sections","aiSiteImportFormsOwed","page","read","forms","place","askedNames","names","sort","sameFields","a","b","one","two","every","aiRebuildImportedForms","firestore","deps","job","hostId","state","org","now","write","writeDraft","inventory","readInventory","orgId","saved","met","pages","some","entry","out","rows","outputs","notes","signature","formId","draft","routing","cannotCollect","fieldName","existing","find","undefined","written","uid","createdBy","formNodeId","consentFieldName","ok","status","Error","slot","op","attempt","creditsSpent","creditsRefunded","resource","versionId","hostSubdomain"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;2CAgB2C,GAE3C,SAASA,UAAU,QAAQ,cAAa;AACxC,SAASC,iBAAiB,EAAEC,4BAA4B,EAAEC,sBAAsB,EAAEC,2BAA2B,QAAQ,+BAA8B;AAEnJ,SAASC,QAAQ,QAAuB,2BAA0B;AAGlE,SAASC,UAAU,QAAQ,qCAAiC;AAC5D,SAASC,iBAAiB,QAAQ,+BAA2B;AAE7D,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,wBAAoB;AACvE,SAASC,YAAY,QAAQ,qBAAiB;AAE9C,oEAAoE,GACpE,OAAO,MAAMC,mCAAmC,eAAc;AAE9D,wCAAwC,GACxC,MAAMC,eAAe;AAErB,gDAAgD,GAChD,OAAO,MAAMC,2BAA2B;IACtCC,SAAS,CAACC,OAAiB,CAAC,WAAW,EAAEA,KAAK,sEAAsE,CAAC;IACrHC,QAAQ;IACRC,UAAU;IACVC,SAAS,CAACC,SAA8B,CAAC,mCAAmC,EAAEA,OAAOC,IAAI,CAAC,QAAQ,oBAAoB,CAAC;AACzH,EAAU;AAEV,MAAMC,QAAQ,CAACC,OAA6B,CAACA,eAAAA,OAAQ,IAAIC,OAAO,CAAC,QAAQ,KAAKC,IAAI;AAElF,sEAAsE,GACtE,SAASC,UAAUC,KAAa;QAChBA;IAAd,MAAMC,SAAQD,eAAAA,MAAME,KAAK,CAAC,4BAAZF,eAAgC,EAAE;IAChD,OAAOC,MAAME,GAAG,CAAC,CAACC,MAAMC;YAA2CD;eAAnCC,OAAO,IAAID,KAAKE,WAAW,KAAK,IAAGF,SAAAA,IAAI,CAAC,EAAE,qBAAPA,OAASG,WAAW,KAAKH,KAAKI,KAAK,CAA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YAAQsB,WAAWd,QAAQc,SAAS;YAAEzC;YAAQ0C,eAAef,QAAQe,aAAa;YAAE9I,OAAO+H,QAAQzJ,IAAI;QAAC;IACnJ;IACA4I,IAAInD,IAAI,GAAG;WAAI,IAAIpC,IAAI0F;KAAO,CAAC1I,IAAI,CAAC,QAAQ;IAC5C,OAAOuI;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-forms.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * A FORM ON A PAGE BROUGHT IN, REBUILT AS THE SITE'S OWN (AGL-4083).\n *\n * A fresh site has no saved form, so an import that placed only a form the\n * site already had left \"Send us a message\" with nothing under it. A form on\n * a page brought in is rebuilt from its fields, by code and with no model:\n * the same fields, required marks and button, built of MUI's separate form\n * elements as the Forms page builds them, and saved as a form draft of the\n * site, as a form job saves one (`aiFormDraft`, `writeAiDraft`). Its answers\n * land in the site's Inbox, and the consent field every form that asks for an\n * email carries takes the place of the source's own marketing box. A form\n * with a password or a card field never gets here: the reader leaves it out.\n *\n * A site that already has this form places it. A site with no room for\n * another keeps the page's words and is told why. The form's id comes from\n * the job and the form's fields, so a pass run twice writes one form.\n *=========================================*/\n\nimport { createHash } from 'node:crypto'\nimport { FORM_COMPONENT_ID, FORM_DISPLAY_NAME_MAX_LENGTH, FORM_INPUT_ELEMENT_IDS, isMarketingConsentFieldName } from '@aglyn/aglyn/app-utils/forms'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport type { AiJob, AiJobItemLedger, AiJobOutput } from '../model/ai-jobs.types'\nimport type { AiSiteImportPage, AiSiteImportState, SiteImportLayout, SiteImportLayoutNode } from '../model/ai-site-import'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport type { SiteImportBlock, SiteImportForm, SiteImportFormField } from '../site-import/site-import-html'\nimport { aiFormDraft, aiFormDraftViolations } from './ai-job-form-step'\nimport { aiJobContentActor, writeAiDraft } from './ai-job-drafts'\n\n/** What a rebuilt form is called where no heading stands above it. */\nexport const AI_SITE_IMPORT_FORM_DEFAULT_NAME = 'Contact form'\n\n/** The node a rebuilt form hangs from. */\nconst FORM_NODE_ID = 'importedForm'\n\n/** Customer-safe sentences, on the page's row. */\nexport const AI_SITE_IMPORT_FORM_COPY = {\n rebuilt: (name: string) => `Your form “${name}” is rebuilt on this page, and what visitors send lands in your Inbox.`,\n noRoom: 'Your plan has no room for another form, so this page’s form is left out. Every word of the page is here.',\n notBuilt: 'This page’s form could not be rebuilt, so it is left out. Every word of the page is here.',\n leftOut: (fields: readonly string[]) => `A form can’t take a file here, so “${fields.join('”, “')}” is left out of it.`,\n} as const\n\nconst clean = (text: string | undefined) => (text ?? '').replace(/\\s+/g, ' ').trim()\n\n/** A field's words in camelCase, for a name a form can submit under. */\nfunction camelCase(words: string): string {\n const parts = words.match(/[A-Za-z0-9]+/g) ?? []\n return parts.map((part, at) => (at === 0 ? part.toLowerCase() : `${part[0]?.toUpperCase()}${part.slice(1).toLowerCase()}`)).join('')\n}\n\n/** The name a field submits under: the source's where it reads as one, else its words'. Never a second of one name. */\nfunction fieldNameOf(field: SiteImportFormField, at: number, taken: Set<string>): string {\n const own = /^[A-Za-z][A-Za-z0-9_-]{0,62}$/.test(field.name) ? field.name : ''\n const base = own || camelCase(field.label ?? '') || `field${at + 1}`\n let name = base\n for (let next = 2; taken.has(name.toLowerCase()); next += 1) name = `${base}${next}`\n taken.add(name.toLowerCase())\n return name\n}\n\n/**\n * A form of a page brought in as a tree of the Form element and MUI's separate\n * form elements: each field a Form Control holding its Form Label and its\n * answer, a lone tick a Choice Label holding one Checkbox, as the Forms page\n * builds them. The tree `aiFormDraft` stamps, binds and declares.\n */\nexport function aiSiteImportFormTree(form: SiteImportForm): { rootId: string; nodes: NodesMap } {\n const { formControl, formLabel, input, select, selectOption, radioGroup, radio, checkbox, choiceLabel, datePicker, timePicker } = FORM_INPUT_ELEMENT_IDS\n const nodes: NodesMap = {}\n const add = (id: string, componentId: string, parentId: string, props: Record<string, unknown>, children: readonly string[] = []) => {\n nodes[id] = { $id: id, type: NodeType.NODE, componentId, pluginId: AI_PALETTE[componentId]?.pluginId, parentId, nodes: [...children], props } as NodesMap[string]\n return id\n }\n const taken = new Set<string>()\n const children = form.fields.map((field, at) => {\n const id = `field${at}`\n const name = fieldNameOf(field, at, taken)\n const label = clean(field.label) || name\n const required = field.required ? { required: true } : {}\n const placeholder = field.placeholder ? { placeholder: field.placeholder } : {}\n const options = (field.options ?? []).map(clean).filter(Boolean)\n const choice = (index: number, words: string, element: string, props: Record<string, unknown>, parent: string) => {\n const box = add(`${id}-opt-${index}-input`, element, `${id}-opt-${index}`, props)\n return add(`${id}-opt-${index}`, choiceLabel, parent, { label: words }, [box])\n }\n // A lone tick is its own question: the words beside it say it all.\n if (field.type === 'checkbox' && options.length <= 1) return choice(0, options[0] ?? label, checkbox, { name, value: options[0] ?? label, ...required }, FORM_NODE_ID)\n const wrapper = (answers: readonly string[]) => add(id, formControl, FORM_NODE_ID, { fullWidth: true, ...required }, [add(`${id}-label`, formLabel, id, { children: label }), ...answers])\n if (field.type === 'checkbox') return wrapper(options.map((option, index) => choice(index, option, checkbox, { name, value: option }, id)))\n if (field.type === 'radio' && options.length) {\n const group = add(`${id}-input`, radioGroup, id, { name }, options.map((option, index) => choice(index, option, radio, { value: option, ...required }, `${id}-input`)))\n return wrapper([group])\n }\n if (field.type === 'select' && options.length) {\n const list = add(`${id}-input`, select, id, { name, fullWidth: true, ...required, ...placeholder }, options.map((option, index) => add(`${id}-opt-${index}`, selectOption, `${id}-input`, { children: option })))\n return wrapper([list])\n }\n if (field.type === 'date' || field.type === 'time') return wrapper([add(`${id}-input`, field.type === 'date' ? datePicker : timePicker, id, { name, ...required })])\n const type = ['email', 'tel', 'url', 'number'].includes(field.type) ? field.type : 'text'\n return wrapper([add(`${id}-input`, input, id, { name, type, ...(field.type === 'textarea' ? { multiline: true, minRows: 3 } : {}), ...placeholder, ...required, fullWidth: true })])\n })\n const submit = clean(form.submit)\n nodes[FORM_NODE_ID] = { $id: FORM_NODE_ID, type: NodeType.NODE, componentId: FORM_COMPONENT_ID, pluginId: AI_PALETTE[FORM_COMPONENT_ID]?.pluginId, nodes: children, props: submit ? { submitLabel: submit } : {} } as NodesMap[string]\n return { rootId: FORM_NODE_ID, nodes }\n}\n\n/** What identifies a form across a site's pages: what it asks and its button, never where it sits. */\nexport function aiSiteImportFormSignature(form: SiteImportForm): string {\n const shape = form.fields.map((field) => [field.type, field.name, clean(field.label), field.required === true, field.options ?? []])\n return createHash('sha256').update(JSON.stringify([shape, clean(form.submit)])).digest('hex').slice(0, 12)\n}\n\n/** Each form of a page's layout, with the nearest heading above it in its section: what it is called. */\nexport function aiSiteImportFormPlaces(layout: SiteImportLayout, blocks: readonly SiteImportBlock[]): Array<{ form: number; heading: string | null }> {\n const places: Array<{ form: number; heading: string | null }> = []\n let heading: string | null = null\n const note = (ref: number) => {\n const block = blocks[ref]\n if (block?.kind === 'heading') heading = clean(block.text) || heading\n }\n const visit = (nodes: readonly SiteImportLayoutNode[]) => {\n for (const node of nodes) {\n if (node.kind === 'line') note(node.line)\n else if (node.kind === 'form') places.push({ form: node.form, heading })\n else if (node.kind === 'row') for (const cell of node.cells) visit(cell.nodes)\n else if (node.kind === 'group') for (const item of node.items) item.lines.forEach(note)\n else if (node.kind === 'tabs') for (const tab of node.tabs) visit(tab.panel)\n }\n }\n for (const section of layout.sections) {\n heading = null\n visit(section.nodes)\n }\n return places\n}\n\n/** The forms of a page still to rebuild or place: each one of its layout that asks something. */\nexport function aiSiteImportFormsOwed(page: Pick<AiSiteImportPage, 'read'>): Array<{ form: number; heading: string | null }> {\n const { read } = page\n if (!read?.layout || !read.forms?.length) return []\n return aiSiteImportFormPlaces(read.layout, read.blocks ?? []).filter((place) => (read.forms?.[place.form]?.fields.length ?? 0) > 0)\n}\n\nconst askedNames = (names: readonly string[]) => names.filter((name) => !isMarketingConsentFieldName(name)).map((name) => name.toLowerCase()).sort()\n\nconst sameFields = (a: readonly string[], b: readonly string[]) => {\n const [one, two] = [askedNames(a), askedNames(b)]\n return one.length === two.length && one.every((name, at) => name === two[at])\n}\n\nexport interface AiSiteImportFormsDeps {\n readInventory?: typeof readSiteInventory\n writeDraft?: typeof writeAiDraft\n}\n\nexport interface AiSiteImportFormsRebuilt {\n /** Each form of the page by its index on the read, and the saved form that takes its place; `null` where none does. */\n forms: Array<{ index: number; formId: string | null }>\n /** A ledger row for each form written, at no credits. */\n rows: AiJobItemLedger[]\n outputs: AiJobOutput[]\n /** What the page's row says of its forms. */\n note: string | null\n}\n\n/**\n * A page's forms as the site's own: one the site already has is placed, and\n * any other is saved as a form of the site (AGL-4083). Pure of any model, so\n * it spends nothing; a site with no room keeps the page's words and is told.\n */\nexport async function aiRebuildImportedForms(\n firestore: FirebaseFirestore.Firestore,\n input: { job: Pick<AiJob, '$id' | 'orgId' | 'createdBy'>; hostId: string; state: AiSiteImportState; page: AiSiteImportPage; org: Partial<AglynOrgBilling> | null; now: Date },\n deps: AiSiteImportFormsDeps = {},\n): Promise<AiSiteImportFormsRebuilt> {\n const { job, hostId, state, page, org, now } = input\n const write = deps.writeDraft ?? writeAiDraft\n const inventory = await (deps.readInventory ?? readSiteInventory)(job.orgId, hostId, { firestore })\n const saved = (inventory?.forms ?? []).map((form) => ({ id: form.id, fields: form.fields ?? [] }))\n let met = state.pages.some((entry) => entry.forms?.length)\n const out: AiSiteImportFormsRebuilt = { forms: [], rows: [], outputs: [], note: null }\n const notes: string[] = []\n for (const place of aiSiteImportFormsOwed(page)) {\n const form = page.read?.forms?.[place.form] as SiteImportForm\n const signature = aiSiteImportFormSignature(form)\n const formId = `${job.$id}-form-${signature}`\n const name = (place.heading ?? '').slice(0, FORM_DISPLAY_NAME_MAX_LENGTH) || AI_SITE_IMPORT_FORM_DEFAULT_NAME\n const draft = aiFormDraft(aiSiteImportFormTree(form), { routing: { kind: 'inbox', list: null }, cannotCollect: [] }, { formId, name })\n const names = draft.fields.map((field) => field.fieldName)\n // A site's only form takes the first form an import meets, as it always has.\n const existing = saved.find((entry) => entry.id === formId || sameFields(entry.fields, names)) ?? (!met && saved.length === 1 ? saved[0] : undefined)\n met = true\n if (existing) {\n out.forms.push({ index: place.form, formId: existing.id })\n continue\n }\n if (aiFormDraftViolations(draft, formId, {}).length) {\n out.forms.push({ index: place.form, formId: null })\n notes.push(AI_SITE_IMPORT_FORM_COPY.notBuilt)\n continue\n }\n const written = await write(firestore, {\n kind: 'form',\n hostId,\n id: formId,\n uid: job.createdBy,\n actor: aiJobContentActor(job),\n org,\n name,\n nodes: draft.nodes,\n form: { rootId: draft.rootId, formNodeId: draft.formNodeId, fields: draft.fields, consentFieldName: draft.consentFieldName, routing: draft.routing },\n now,\n })\n if (written.ok === false) {\n if (written.status === 404) throw new Error(`site ${hostId} vanished while its form was rebuilt`)\n out.forms.push({ index: place.form, formId: null })\n notes.push(AI_SITE_IMPORT_FORM_COPY.noRoom)\n continue\n }\n saved.push({ id: formId, fields: names })\n out.forms.push({ index: place.form, formId })\n notes.push(AI_SITE_IMPORT_FORM_COPY.rebuilt(written.name))\n if (form.leftOut?.length) notes.push(AI_SITE_IMPORT_FORM_COPY.leftOut(form.leftOut))\n out.rows.push({ slot: `form-${signature}`, op: 'form', label: written.name, status: 'succeeded', attempt: 1, creditsSpent: 0, creditsRefunded: 0, outputs: [formId] })\n out.outputs.push({ resource: 'form', id: formId, versionId: written.versionId, hostId, hostSubdomain: written.hostSubdomain, label: written.name })\n }\n out.note = [...new Set(notes)].join(' ') || null\n return out\n}\n"],"names":["createHash","FORM_COMPONENT_ID","FORM_DISPLAY_NAME_MAX_LENGTH","FORM_INPUT_ELEMENT_IDS","isMarketingConsentFieldName","NodeType","AI_PALETTE","readSiteInventory","aiFormDraft","aiFormDraftViolations","aiJobContentActor","writeAiDraft","AI_SITE_IMPORT_FORM_DEFAULT_NAME","FORM_NODE_ID","AI_SITE_IMPORT_FORM_COPY","rebuilt","name","noRoom","notBuilt","leftOut","fields","join","clean","text","replace","trim","camelCase","words","parts","match","map","part","at","toLowerCase","toUpperCase","slice","fieldNameOf","field","taken","own","test","base","label","next","has","add","aiSiteImportFormTree","form","formControl","formLabel","input","select","selectOption","radioGroup","radio","checkbox","choiceLabel","datePicker","timePicker","nodes","id","componentId","parentId","props","children","$id","type","NODE","pluginId","Set","options","required","placeholder","filter","Boolean","choice","index","element","parent","box","length","value","wrapper","answers","fullWidth","option","group","list","includes","multiline","minRows","submit","submitLabel","rootId","aiSiteImportFormSignature","shape","update","JSON","stringify","digest","aiSiteImportFormPlaces","layout","blocks","places","heading","note","ref","block","kind","visit","node","line","push","cell","cells","item","items","lines","forEach","tab","tabs","panel","section","sections","aiSiteImportFormsOwed","page","read","forms","place","askedNames","names","sort","sameFields","a","b","one","two","every","aiRebuildImportedForms","firestore","deps","job","hostId","state","org","now","write","writeDraft","inventory","readInventory","orgId","saved","met","pages","some","entry","out","rows","outputs","notes","signature","formId","draft","routing","cannotCollect","fieldName","existing","find","undefined","written","uid","createdBy","actor","formNodeId","consentFieldName","ok","status","Error","slot","op","attempt","creditsSpent","creditsRefunded","resource","versionId","hostSubdomain"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;2CAgB2C,GAE3C,SAASA,UAAU,QAAQ,cAAa;AACxC,SAASC,iBAAiB,EAAEC,4BAA4B,EAAEC,sB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puts(state: AiSiteImportState, wave:
|
|
|
38
38
|
* came in. The job's earlier publish is carried in the answer.
|
|
39
39
|
*/
|
|
40
40
|
export declare function aiPublishImportedWave(firestore: FirebaseFirestore.Firestore, input: {
|
|
41
|
-
job: Pick<AiJob, '$id' | 'orgId' | 'hostId'> & Partial<Pick<AiJob, 'inputs' | 'sitePublish'>>;
|
|
41
|
+
job: Pick<AiJob, '$id' | 'orgId' | 'hostId' | 'createdBy'> & Partial<Pick<AiJob, 'inputs' | 'sitePublish'>>;
|
|
42
42
|
state: AiSiteImportState;
|
|
43
43
|
wave: AiSiteImportWave;
|
|
44
44
|
items: readonly AiJobItemLedger[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-publish.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * EACH WAVE LANDS IN THE SITE'S PREVIEW (AGL-4084).\n *\n * A site brought in starts in preview (AGL-4086, `host.preview`): the public\n * sees its notice, and its team sees the whole site. So when a wave closes,\n * its pages go live INTO THE PREVIEW through the same writes a guided\n * start's publish makes (`aiPublishGuidedSite`): each page takes its\n * address, Home takes `/`, a link to a page that will not come in goes\n * nowhere with its words kept, and the cached pages go. A link to a page of a\n * later wave keeps its place (AGL-4107): until that page is live a visitor\n * sees its words, and once the page's wave lands it goes there. The team opens the site and sees the wave; the public\n * still sees the notice until the person makes the site public.\n *\n * Only into a preview. A site that is not in preview keeps the wave's pages\n * as drafts, as every import did before: the public never sees a page no\n * person has looked at. And `site_published` is not sent here: the site is\n * published when its switch makes it public (AGL-4086), not when a wave\n * lands.\n *=========================================*/\n\nimport { isHostInPreview } from '@aglyn/aglyn/app-utils/site-preview'\nimport type { AiJob, AiJobItemLedger, AiJobOutput, AiJobSitePublish } from '../model/ai-jobs.types'\nimport type { AiSiteImportState, AiSiteImportWave } from '../model/ai-site-import'\nimport { aiMergeSitePublish, aiPublishGuidedSite, type AiSitePublishDeps } from './ai-site-publish'\n\nexport interface AiSiteImportPublishDeps {\n publish?: typeof aiPublishGuidedSite\n /** Whether the site is in preview now. */\n inPreview?: (firestore: FirebaseFirestore.Firestore, hostId: string) => Promise<boolean>\n}\n\nasync function readInPreview(firestore: FirebaseFirestore.Firestore, hostId: string): Promise<boolean> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists && isHostInPreview({ preview: host.get('preview') })\n}\n\nconst delivered = (row: AiJobItemLedger | undefined) => row?.status === 'succeeded' || row?.status === 'degraded'\n\nconst open = (row: AiJobItemLedger | undefined) => row?.status === 'pending' || row?.status === 'running'\n\n/**\n * The pages of the import that will never be in (AGL-4107): left out, or\n * settled without coming in — a wave's own failures included. A page of a\n * wave still to come is not one: a link to it keeps its place and shows its\n * words, which the site's pages show for a page that is not live, and goes\n * there once that page's wave lands.\n */\nexport function aiSiteImportUnbuilt(state: AiSiteImportState, items: readonly AiJobItemLedger[]): string[] {\n const rows = new Map(items.map((row) => [row.slot, row]))\n return state.pages\n .filter((page) => {\n const row = rows.get(page.slot)\n return page.refused || (!delivered(row) && !open(row))\n })\n .map((page) => page.draftId)\n}\n\n/** The wave's pages that came in, as the outputs that publish them, in the wave's order. */\nexport function aiSiteImportWaveOutputs(\n state: AiSiteImportState,\n wave: AiSiteImportWave,\n items: readonly AiJobItemLedger[],\n outputs: readonly AiJobOutput[],\n): AiJobOutput[] {\n const rows = new Map(items.map((row) => [row.slot, row]))\n return wave.slots.flatMap((slot) => {\n const page = state.pages.find((entry) => entry.slot === slot)\n if (!page || !delivered(rows.get(slot))) return []\n const output = outputs.find((entry) => entry.resource === 'screen' && entry.id === page.draftId)\n return output ? [output] : []\n })\n}\n\n/**\n * A closed wave's pages, live in the site's preview (AGL-4084). `null` when\n * nothing went live: the site is not in preview, or none of the wave's pages\n * came in. The job's earlier publish is carried in the answer.\n */\nexport async function aiPublishImportedWave(\n firestore: FirebaseFirestore.Firestore,\n input: {\n job: Pick<AiJob, '$id' | 'orgId' | 'hostId'> & Partial<Pick<AiJob, 'inputs' | 'sitePublish'>>\n state: AiSiteImportState\n wave: AiSiteImportWave\n items: readonly AiJobItemLedger[]\n outputs: readonly AiJobOutput[]\n now: Date\n },\n deps: AiSiteImportPublishDeps = {},\n): Promise<AiJobSitePublish | null> {\n const hostId = input.job.hostId\n if (!hostId) return null\n const pages = aiSiteImportWaveOutputs(input.state, input.wave, input.items, input.outputs)\n if (!pages.length) return null\n if (!(await (deps.inPreview ?? readInPreview)(firestore, hostId))) return null\n const publishDeps: AiSitePublishDeps = {\n // Published when its switch makes it public (AGL-4086), never when a wave lands.\n sendSitePublished: async () => undefined,\n }\n const already = input.job.sitePublish ?? null\n const result = await (deps.publish ?? aiPublishGuidedSite)(\n firestore,\n {\n job: input.job,\n outputs: pages,\n now: input.now,\n // The links to a page that did not come in go nowhere, their words kept;\n // a page still to come keeps its links (AGL-4107).\n unbuiltScreenIds: aiSiteImportUnbuilt(input.state, input.items),\n keepLinkWords: true,\n siteOrder: input.state.pages.map((page) => page.draftId),\n // A later wave joins what is live: it never takes the home address again.\n ...(already?.published.length ? { retry: true } : {}),\n },\n publishDeps,\n )\n return already ? aiMergeSitePublish(already, result) : result\n}\n"],"names":["isHostInPreview","aiMergeSitePublish","aiPublishGuidedSite","readInPreview","firestore","hostId","host","collection","doc","get","exists","preview","delivered","row","status","open","aiSiteImportUnbuilt","state","items","rows","Map","map","slot","pages","filter","page","refused","draftId","aiSiteImportWaveOutputs","wave","outputs","slots","flatMap","find","entry","output","resource","id","aiPublishImportedWave","input","deps","job","length","inPreview","publishDeps","sendSitePublished","undefined","already","sitePublish","result","publish","now","unbuiltScreenIds","keepLinkWords","siteOrder","published","retry"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;2CAkB2C,GAE3C,SAASA,eAAe,QAAQ,sCAAqC;AAGrE,SAASC,kBAAkB,EAAEC,mBAAmB,QAAgC,uBAAmB;AAQnG,eAAeC,cAAcC,SAAsC,EAAEC,MAAc;IACjF,MAAMC,OAAO,MAAMF,UAAUG,UAAU,CAAC,SAASC,GAAG,CAACH,QAAQI,GAAG;IAChE,OAAOH,KAAKI,MAAM,IAAIV,gBAAgB;QAAEW,SAASL,KAAKG,GAAG,CAAC;IAAW;AACvE;AAEA,MAAMG,YAAY,CAACC,MAAqCA,CAAAA,uBAAAA,IAAKC,MAAM,MAAK,eAAeD,CAAAA,uBAAAA,IAAKC,MAAM,MAAK;AAEvG,MAAMC,OAAO,CAACF,MAAqCA,CAAAA,uBAAAA,IAAKC,MAAM,MAAK,aAAaD,CAAAA,uBAAAA,IAAKC,MAAM,MAAK;AAEhG;;;;;;CAMC,GACD,OAAO,SAASE,oBAAoBC,KAAwB,EAAEC,KAAiC;IAC7F,MAAMC,OAAO,IAAIC,IAAIF,MAAMG,GAAG,CAAC,CAACR,MAAQ;YAACA,IAAIS,IAAI;YAAET;SAAI;IACvD,OAAOI,MAAMM,KAAK,CACfC,MAAM,CAAC,CAACC;QACP,MAAMZ,MAAMM,KAAKV,GAAG,CAACgB,KAAKH,IAAI;QAC9B,OAAOG,KAAKC,OAAO,IAAK,CAACd,UAAUC,QAAQ,CAACE,KAAKF;IACnD,GACCQ,GAAG,CAAC,CAACI,OAASA,KAAKE,OAAO;AAC/B;AAEA,0FAA0F,GAC1F,OAAO,SAASC,wBACdX,KAAwB,EACxBY,IAAsB,EACtBX,KAAiC,EACjCY,OAA+B;IAE/B,MAAMX,OAAO,IAAIC,IAAIF,MAAMG,GAAG,CAAC,CAACR,MAAQ;YAACA,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KAAK;QAC9DmC,eAAe;QACfC,WAAWf,MAAMtB,KAAK,CAACM,KAAK,CAACF,GAAG,CAAC,CAACI,OAASA,KAAKE,OAAO;OAEnDoB,CAAAA,2BAAAA,QAASQ,SAAS,CAACb,MAAM,IAAG;QAAEc,OAAO;IAAK,IAAI,CAAC,IAErDZ;IAEF,OAAOG,UAAU9C,mBAAmB8C,SAASE,UAAUA;AACzD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-publish.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * EACH WAVE LANDS IN THE SITE'S PREVIEW (AGL-4084).\n *\n * A site brought in starts in preview (AGL-4086, `host.preview`): the public\n * sees its notice, and its team sees the whole site. So when a wave closes,\n * its pages go live INTO THE PREVIEW through the same writes a guided\n * start's publish makes (`aiPublishGuidedSite`): each page takes its\n * address, Home takes `/`, a link to a page that will not come in goes\n * nowhere with its words kept, and the cached pages go. A link to a page of a\n * later wave keeps its place (AGL-4107): until that page is live a visitor\n * sees its words, and once the page's wave lands it goes there. The team opens the site and sees the wave; the public\n * still sees the notice until the person makes the site public.\n *\n * Only into a preview. A site that is not in preview keeps the wave's pages\n * as drafts, as every import did before: the public never sees a page no\n * person has looked at. And `site_published` is not sent here: the site is\n * published when its switch makes it public (AGL-4086), not when a wave\n * lands.\n *=========================================*/\n\nimport { isHostInPreview } from '@aglyn/aglyn/app-utils/site-preview'\nimport type { AiJob, AiJobItemLedger, AiJobOutput, AiJobSitePublish } from '../model/ai-jobs.types'\nimport type { AiSiteImportState, AiSiteImportWave } from '../model/ai-site-import'\nimport { aiMergeSitePublish, aiPublishGuidedSite, type AiSitePublishDeps } from './ai-site-publish'\n\nexport interface AiSiteImportPublishDeps {\n publish?: typeof aiPublishGuidedSite\n /** Whether the site is in preview now. */\n inPreview?: (firestore: FirebaseFirestore.Firestore, hostId: string) => Promise<boolean>\n}\n\nasync function readInPreview(firestore: FirebaseFirestore.Firestore, hostId: string): Promise<boolean> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists && isHostInPreview({ preview: host.get('preview') })\n}\n\nconst delivered = (row: AiJobItemLedger | undefined) => row?.status === 'succeeded' || row?.status === 'degraded'\n\nconst open = (row: AiJobItemLedger | undefined) => row?.status === 'pending' || row?.status === 'running'\n\n/**\n * The pages of the import that will never be in (AGL-4107): left out, or\n * settled without coming in — a wave's own failures included. A page of a\n * wave still to come is not one: a link to it keeps its place and shows its\n * words, which the site's pages show for a page that is not live, and goes\n * there once that page's wave lands.\n */\nexport function aiSiteImportUnbuilt(state: AiSiteImportState, items: readonly AiJobItemLedger[]): string[] {\n const rows = new Map(items.map((row) => [row.slot, row]))\n return state.pages\n .filter((page) => {\n const row = rows.get(page.slot)\n return page.refused || (!delivered(row) && !open(row))\n })\n .map((page) => page.draftId)\n}\n\n/** The wave's pages that came in, as the outputs that publish them, in the wave's order. */\nexport function aiSiteImportWaveOutputs(\n state: AiSiteImportState,\n wave: AiSiteImportWave,\n items: readonly AiJobItemLedger[],\n outputs: readonly AiJobOutput[],\n): AiJobOutput[] {\n const rows = new Map(items.map((row) => [row.slot, row]))\n return wave.slots.flatMap((slot) => {\n const page = state.pages.find((entry) => entry.slot === slot)\n if (!page || !delivered(rows.get(slot))) return []\n const output = outputs.find((entry) => entry.resource === 'screen' && entry.id === page.draftId)\n return output ? [output] : []\n })\n}\n\n/**\n * A closed wave's pages, live in the site's preview (AGL-4084). `null` when\n * nothing went live: the site is not in preview, or none of the wave's pages\n * came in. The job's earlier publish is carried in the answer.\n */\nexport async function aiPublishImportedWave(\n firestore: FirebaseFirestore.Firestore,\n input: {\n job: Pick<AiJob, '$id' | 'orgId' | 'hostId' | 'createdBy'> & Partial<Pick<AiJob, 'inputs' | 'sitePublish'>>\n state: AiSiteImportState\n wave: AiSiteImportWave\n items: readonly AiJobItemLedger[]\n outputs: readonly AiJobOutput[]\n now: Date\n },\n deps: AiSiteImportPublishDeps = {},\n): Promise<AiJobSitePublish | null> {\n const hostId = input.job.hostId\n if (!hostId) return null\n const pages = aiSiteImportWaveOutputs(input.state, input.wave, input.items, input.outputs)\n if (!pages.length) return null\n if (!(await (deps.inPreview ?? readInPreview)(firestore, hostId))) return null\n const publishDeps: AiSitePublishDeps = {\n // Published when its switch makes it public (AGL-4086), never when a wave lands.\n sendSitePublished: async () => undefined,\n }\n const already = input.job.sitePublish ?? null\n const result = await (deps.publish ?? aiPublishGuidedSite)(\n firestore,\n {\n job: input.job,\n outputs: pages,\n now: input.now,\n // The links to a page that did not come in go nowhere, their words kept;\n // a page still to come keeps its links (AGL-4107).\n unbuiltScreenIds: aiSiteImportUnbuilt(input.state, input.items),\n keepLinkWords: true,\n siteOrder: input.state.pages.map((page) => page.draftId),\n // A later wave joins what is live: it never takes the home address again.\n ...(already?.published.length ? { retry: true } : {}),\n },\n publishDeps,\n )\n return already ? aiMergeSitePublish(already, result) : result\n}\n"],"names":["isHostInPreview","aiMergeSitePublish","aiPublishGuidedSite","readInPreview","firestore","hostId","host","collection","doc","get","exists","preview","delivered","row","status","open","aiSiteImportUnbuilt","state","items","rows","Map","map","slot","pages","filter","page","refused","draftId","aiSiteImportWaveOutputs","wave","outputs","slots","flatMap","find","entry","output","resource","id","aiPublishImportedWave","input","deps","job","length","inPreview","publishDeps","sendSitePublished","undefined","already","sitePublish","result","publish","now","unbuiltScreenIds","keepLinkWords","siteOrder","published","retry"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;2CAkB2C,GAE3C,SA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Ec,OAAO;IAAK,IAAI,CAAC,IAErDZ;IAEF,OAAOG,UAAU9C,mBAAmB8C,SAASE,UAAUA;AACzD"}
|
|
@@ -23,7 +23,7 @@ import { aiSiteWords } from "../model/ai-site-job.js";
|
|
|
23
23
|
import { aiSiteIsStarterSrc, aiSitePhotosLastRefusalMs } from "../model/ai-site-photos.js";
|
|
24
24
|
import { AI_DATASET_DRAFT_RESOURCE } from "./ai-build-unit-outcome.js";
|
|
25
25
|
import { aiOriginJobId } from "./ai-job-draft-ids.js";
|
|
26
|
-
import { readAiDraftNodes, updateAiDraftNodes } from "./ai-job-drafts.js";
|
|
26
|
+
import { aiJobContentActor, readAiDraftNodes, updateAiDraftNodes } from "./ai-job-drafts.js";
|
|
27
27
|
import { aiSiteProductPhotoSrc } from "./ai-job-site-content.js";
|
|
28
28
|
import { aiSiteDatasetPlacedPhotoDetails, aiSiteDatasetRecordsFromOwn } from "./ai-job-site-datasets.js";
|
|
29
29
|
import { AI_LAYOUT_STOCK_MAX_BYTES, AI_STOCK_PHOTO_OWN_REFUSALS, aiStockIngestRequest, aiStockPhotoAlt, aiStockPhotoWordsOf, aiStockPlacedPhotos, aiStockProperWords } from "./ai-layout-stock-photos.js";
|
|
@@ -378,6 +378,7 @@ import { AI_LAYOUT_STOCK_MAX_BYTES, AI_STOCK_PHOTO_OWN_REFUSALS, aiStockIngestRe
|
|
|
378
378
|
kind: 'screen',
|
|
379
379
|
hostId,
|
|
380
380
|
id: page.screen,
|
|
381
|
+
actor: aiJobContentActor(job),
|
|
381
382
|
now: input.now,
|
|
382
383
|
update: (current)=>aiSitePageWithPhotos(current, plan)
|
|
383
384
|
}) : null;
|