Files
ipal-kit/src/modules/starter/generate.ts
T
Radosław SmolińskiandClaude Opus 5.5 e7e756a0d7 starter:gate: a fresh tarball every run and proof of which code made the site
pnpm's dlx cache is keyed by the spec, so the gate reused the previous run's plugin when the
tarball path stayed the same. Each run now packs to a new file name and calls dlx with
--config.dlx-cache-max-age=0. build:starter records the plugin commit in the bundle; ipal-kit
create records the bundle's sha256 and that commit in .ipal/starter.json; the gate checks both,
and the installed plugin, against the packed tarball.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:30:24 +01:00

253 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Files and sections the starter writes from the answers instead of copying them from the reference
* site: the language list, the brand tokens and DESIGN.md, the AGENTS.md decisions, ipal-doctor.json,
* the fonts in the root layout and the package.json rewrite.
*/
import type { StarterAnswers } from './answers.js'
export type SiteContext = {
/** `YYYY-MM-DD`, the day the site is created. */
date: string
dbNames: { dev: string; prod: string }
domain: string
/** The exact ipal-kit version written into package.json. */
pluginVersion: string
serverUrl: string
/** Which starter bundle made the site (recorded in `.ipal/starter.json`; the release gate compares it). */
source?: { bundleSha256: string; commit: null | string }
}
const q = (value: string) => `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
export function renderI18nConfig(a: StarterAnswers): string {
const locales = a.languages.locales.map((l) => ` { code: ${q(l.code)}, label: ${q(l.label)} },`).join('\n')
return `import type { I18nConfig } from '@intecion/ipal-kit'
/** The ONLY source of languages (AGENT.md §3). Every language has a URL prefix: ${a.languages.locales.map((l) => `/${l.code}/…`).join(', ')}. */
export const i18nConfig = {
defaultLocale: ${q(a.languages.default)},
locales: [
${locales}
],
} as const satisfies I18nConfig
export type Locale = (typeof i18nConfig.locales)[number]['code']
`
}
const RADIUS = { round: { card: '1.25rem', control: '999px' }, sharp: { card: '0.25rem', control: '0.25rem' }, soft: { card: '0.75rem', control: '0.5rem' } }
export function renderTokens(a: StarterAnswers): string {
const s = a.styling
const light = [` primary: ${q(s.primary)},`]
if (s.secondary) {light.push(` secondary: ${q(s.secondary)},`)}
if (s.accent) {light.push(` accent: ${q(s.accent)},`)}
const radius = RADIUS[s.radius]
return `// src/design/tokens.ts — the ONLY file edited to rebrand the site (docs/design-tokens.md).
// After every change: \`pnpm tokens\` → writes src/design/tokens.css (commit it) and prints the WCAG contrast check.
// Leave out anything the brand does not change: the neutral defaults in @intecion/ipal-kit/tokens.css apply.
import { defineTokens } from '@intecion/ipal-kit/tokens'
export const tokens = defineTokens({
theme: ${q(s.theme)}, // must match Site settings → Theme
fluid: ${q(s.fluid)},
color: {
light: {
${light.join('\n')}
},
dark: {
// brand roles carry over from light; set a lighter primary here if the contrast report fails
},
},
radius: { card: ${q(radius.card)}, control: ${q(radius.control)} }, // "${s.radius}"
})
`
}
export function renderDesignMd(a: StarterAnswers): string {
const s = a.styling
const radius = RADIUS[s.radius]
const toggle = s.theme === 'both' ? 'yes' : 'no'
return `# DESIGN.md — ${a.siteName}
The human source of the look. Its machine form is \`src/design/tokens.ts\`; the two must agree
(\`ipal-doctor\` compares them). Values go into \`tokens.ts\`, never into components.
Sections are fixed: fill every one, write "default" where the brand keeps the standard.
## 1. Brand in one sentence
[TO FILL: what the site is, for whom, the feeling]. Industry: ${a.industry}. Market: ${a.market}.
The one memorable element (where the boldness goes): [TO FILL]. Everything else stays quiet.
## 2. Colour
| Role (\`--ipal-*\`) | Light | Dark | Used for |
|---|---|---|---|
| primary | ${s.primary} | (carried over) | main buttons, key accents |
| secondary | ${s.secondary ?? 'default'} | default | second button |
| accent | ${s.accent ?? 'default (= primary)'} | | badges, highlights |
| bg / surface / surface-muted | default | default | page, cards, alternate sections |
Contrast (paste \`pnpm exec ipal-tokens --report\`; every ✗ fixed before launch):
\`\`\`
[TO FILL: report]
\`\`\`
## 3. Type
Body: ${s.fontBody} (\`--font-family-body\`). Headings: ${s.fontHeading} (\`--font-family-heading\`).
Max 2 families × 2–3 weights, \`subsets: ['latin', 'latin-ext']\`. Scale overrides (\`fs\`): none.
## 4. Shape and depth
Radius: "${s.radius}" — control ${radius.control}, card ${radius.card}, media default. Depth: [TO FILL].
## 5. Layout
Scale: ${s.fluid === 'wide' ? 'fluid-wide (to 1920px)' : 'fluid (to 1280px)'}. Container default, narrow default (legal, articles), measure 68ch.
Section rhythm: py-section; compact bands py-section-sm.
## 6. Motion
Durations: default (fast 150 / base 250 / slow 400 ms). Reduced motion: every duration token is 0 ms.
## 7. Imagery and icons
Photo style: [TO FILL]. Focal points set in Media. Icons: lucide set.
## 8. Theme
${s.theme === 'both' ? 'light and dark' : `${s.theme} only`}, default ${s.defaultTheme} (Site settings → Theme), toggle ${toggle}.
## 9. Deviations from the standard
- none
`
}
const yesNo = (v: boolean) => (v ? 'on' : 'off')
function agencyText(agency: StarterAnswers['admin']['agency']): string {
if (agency === 'intecion') {return 'Intecion technology credit (default)'}
if (agency === 'none') {return 'no agency credit (`agency: false`)'}
return `agency credit ${agency.name} (${agency.url})`
}
/** The "Project decisions" lines — one per architecture topic, the owner's answers only. */
export function renderDecisions(a: StarterAnswers, ctx: SiteContext): string {
const lines = [
`- Languages: ${a.languages.locales.map((l) => l.code).join(', ')} (default ${a.languages.default}), every language with a URL prefix; \`/\` redirects to \`/${a.languages.default}\`.`,
`- Styling: the ipal-kit token standard (\`src/design/tokens.ts\` → \`pnpm tokens\`); primary ${a.styling.primary}${a.styling.secondary ? `, secondary ${a.styling.secondary}` : ''}${a.styling.accent ? `, accent ${a.styling.accent}` : ''}; ${a.styling.fontBody} (body) + ${a.styling.fontHeading} (headings); radius ${a.styling.radius}; ${a.styling.fluid === 'wide' ? 'fluid-wide' : 'fluid'}; theme ${a.styling.theme}, default ${a.styling.defaultTheme}.`,
`- Pages and content: ${a.content.pages.join('; ')}. Collections: ${a.content.collections.length ? a.content.collections.join(', ') : 'none'}.`,
`- Forms: ${a.forms.list.length ? a.forms.list.join(', ') : 'none'}; submissions to ${a.forms.recipient}; e-mail via ${a.forms.transport === 'graph' ? 'Microsoft Graph' : 'SMTP from Site integrations'}; Turnstile on.`,
`- Analytics and consent: ${a.consent.tools.length ? a.consent.tools.join(', ') : 'no analytics tools'}; Consent Mode ${a.consent.consentMode}; banner \`settings="${a.consent.banner}"\`; consent log on; cookie scanner ${yesNo(a.consent.cookieScanner)}${a.consent.cookieScanner ? `, crawl ${yesNo(a.consent.crawl)}` : ` — ${a.consent.cookieScannerOffReason}`}.`,
`- SEO/GEO: market ${a.market}; ${a.seo.localBusiness ? `local business (${a.seo.localBusiness.type} JSON-LD from the Company global)` : 'no local business'}; llms.txt, llms-full.txt, Markdown and MCP on; AI bots ${a.seo.aiBots}${a.seo.aiBots === 'allow' ? '' : ` — ${a.seo.aiBotsReason}`}.`,
`- Database and media: MongoDB only; database names from \`databaseNamesFor('${ctx.domain}')\` → \`${ctx.dbNames.dev}\` / \`${ctx.dbNames.prod}\`; media ${a.media === 'r2' ? 'on Cloudflare R2 in production (R2_PUBLIC_URL empty = served by the app), local disk in dev' : 'on local disk — a Coolify persistent volume in production'}.`,
`- Admin: 2FA ${a.admin.twoFactor ? `on (issuer "${a.siteName}")` : `off — ${a.admin.twoFactorOffReason}`}; white-label ${yesNo(a.admin.whiteLabel)}; adminMeta ${a.admin.adminMeta ? 'on' : `off — ${a.admin.adminMetaOffReason}`}; ${agencyText(a.admin.agency)}.`,
`- Hosting: Coolify (${a.hosting.coolify}) — build and check locally, Coolify builds the app from the repo with its default build pack, MongoDB is a separate Coolify resource on the same Docker network; no Dockerfile (docs/DEPLOY.md). Canonical ${ctx.serverUrl}${a.hosting.canonical === 'www' ? ' (apex redirects to www)' : ' (www redirects to apex)'}. DNS: ${a.hosting.dns}.`,
`- CSP: report-only at the start; switch to \`mode: 'enforce'\` in next.config.ts once the \`[csp]\` reports are clean (security.md → ROLL OUT CSP).`,
'- Approved exception: the `/design` styleguide has its labels in code (token names, a technical page, noindex) — the "texts from the panel" rule does not apply to it.',
'- Approved exception: `ALLOW_LOCAL_MEDIA=1` (instrumentation.ts, next.config.ts) lets a production build run without R2 for local checks and CI only; never set in Coolify.',
`- Agent tooling: skills in \`.agents/skills\`${a.tooling.external.length ? `; external skills ${a.tooling.external.join(', ')}` : '; no external skills'}.`,
`- Created with \`ipal-kit create\` ${ctx.pluginVersion} on ${ctx.date}.`,
]
const skip = auditSkips(a)
if (skip.length) {lines.push(`- ipal-audit-skip: ${skip.map((s) => s.key).join(', ')} — ${skip.map((s) => s.reason).join('; ')}`)}
return `## Project decisions\n${lines.join('\n')}\n`
}
/** Modules the owner turned off: the `ipal-audit-skip` keys and the matching ipal-doctor rules. */
function auditSkips(a: StarterAnswers): { doctor?: string; key: string; reason: string }[] {
const out: { doctor?: string; key: string; reason: string }[] = []
if (!a.admin.twoFactor) {out.push({ doctor: '2fa', key: 'twofactor', reason: a.admin.twoFactorOffReason ?? '' })}
if (a.media === 'local') {out.push({ key: 'r2', reason: 'media on a Coolify persistent volume (owner\'s choice)' })}
if (a.seo.aiBots !== 'allow') {out.push({ key: 'aibots', reason: a.seo.aiBotsReason ?? '' })}
return out
}
/** AGENTS.md: the reference header and site map replaced, the decisions block filled from the answers. */
export function renderAgentsMd(reference: string, a: StarterAnswers, ctx: SiteContext): string {
const start = '<!-- starter:decisions -->'
const end = '<!-- /starter:decisions -->'
const from = reference.indexOf(start)
const to = reference.indexOf(end)
const rules = reference.indexOf('## Rules')
const map = reference.indexOf('## Site map')
if (from < 0 || to < from || rules < 0 || map < rules || map > from) {
throw new Error('reference AGENTS.md: expected "## Rules", "## Site map" and the <!-- starter:decisions --> block, in that order')
}
const header = `# AGENTS.md
**Project:** ${a.siteName} · ${ctx.domain} · market ${a.market} · industry ${a.industry}
**Languages:** ${a.languages.locales.map((l) => (l.code === a.languages.default ? `${l.code} (default)` : l.code)).join(', ')} · **Media:** ${a.media === 'r2' ? 'R2' : 'local disk (Coolify volume)'} · **Email:** ${a.forms.transport === 'graph' ? 'Microsoft Graph' : 'SMTP from Site integrations'}
`
const siteMap = `## Site map\n${a.content.pages.map((p) => `- ${p}`).join('\n')}\n\n`
return header + reference.slice(rules, map) + siteMap + start + '\n' + renderDecisions(a, ctx) + reference.slice(to)
}
type DoctorRule = { [key: string]: unknown; off?: boolean; reason: string; until?: string }
/**
* ipal-doctor.json: the domain, not launched yet, and every deliberate difference silenced with its reason —
* the reference site's own silences (`inherited`, from its ipal-doctor.json) while the files they cover are in
* the site, CSP report-only for 28 days, and each module the owner turned off. A temporary silence of the
* reference site (one with `until`, a follow-up of its own) is not inherited: a new site starts with that check on.
*/
export function renderDoctorConfig(a: StarterAnswers, ctx: SiteContext, inherited: Record<string, DoctorRule> = {}): string {
const until = new Date(`${ctx.date}T00:00:00Z`)
until.setUTCDate(until.getUTCDate() + 28)
const kept = Object.entries(inherited)
.filter(([, rule]) => !rule.until)
.filter(([id]) => id !== 'audit:collections-present' || a.content.collections.length > 0)
const rules: Record<string, DoctorRule> = {
...Object.fromEntries(kept),
csp: { off: true, reason: 'report-only at the start; switch to enforce once the [csp] reports are clean (security.md → ROLL OUT CSP)', until: until.toISOString().slice(0, 10) },
}
for (const skip of auditSkips(a)) {
if (skip.doctor) {rules[skip.doctor] = { off: true, reason: skip.reason }}
}
if (!a.consent.cookieScanner) {rules['cookie-scanner'] = { off: true, reason: a.consent.cookieScannerOffReason ?? '' }}
if (!a.admin.adminMeta) {rules['admin-meta'] = { off: true, reason: a.admin.adminMetaOffReason ?? '' }}
else if (a.admin.agency === 'none') {rules['admin-meta'] = { off: true, reason: 'no agency credit (owner\'s choice)' }}
return `${JSON.stringify({ domain: ctx.domain, launched: false, rules }, null, 2)}\n`
}
/** `Open Sans` → `Open_Sans` (the next/font/google export name). */
export function fontExport(name: string): string {
return name.trim().replace(/\s+/g, '_')
}
/** Points the root layout's two next/font calls (`const body = X(…)`, `const heading = Y(…)`) at the answered fonts. */
export function rewriteFonts(layout: string, a: StarterAnswers): string {
const body = fontExport(a.styling.fontBody)
const heading = fontExport(a.styling.fontHeading)
const importLine = /^import \{[^}]*\} from 'next\/font\/google'$/m
const bodyCall = /^const body = \w+\(/m
const headingCall = /^const heading = \w+\(/m
if (!importLine.test(layout) || !bodyCall.test(layout) || !headingCall.test(layout)) {
throw new Error('reference layout: expected the next/font/google import and `const body = …(` / `const heading = …(`')
}
const names = [...new Set([body, heading])].sort()
return layout
.replace(importLine, `import { ${names.join(', ')} } from 'next/font/google'`)
.replace(bodyCall, `const body = ${body}(`)
.replace(headingCall, `const heading = ${heading}(`)
}
/**
* The manifest's package.json rewrite: `"section.key": value` sets one entry, `null` removes it.
* The value `<exact released version>` becomes the plugin version.
*/
export function rewritePackageJson(text: string, rules: Record<string, null | string>, ctx: SiteContext, a: StarterAnswers): string {
const pkg = JSON.parse(text) as Record<string, unknown>
for (const [path, value] of Object.entries(rules)) {
const dot = path.indexOf('.')
if (dot < 0) {
if (value === null) {delete pkg[path]}
else {pkg[path] = value}
continue
}
const section = path.slice(0, dot)
const key = path.slice(dot + 1)
const target = (pkg[section] ?? {}) as Record<string, unknown>
if (value === null) {delete target[key]}
else {target[key] = value === '<exact released version>' ? ctx.pluginVersion : value}
if (Object.keys(target).length) {pkg[section] = target}
else {delete pkg[section]}
}
pkg.description = `${a.siteName} — ${ctx.domain} (Payload CMS 3 + Next 16 on @intecion/ipal-kit)`
return `${JSON.stringify(pkg, null, 2)}\n`
}