Project starter: ipal-kit create <domain> generates a new site from the reference site
- bin `ipal-kit` (subcommand `create`): the architecture questions (or --answers JSON), rendering from reference/ through starter.manifest.json (placeholders, @starter:if variants, //: alternatives, demo dropped), answers into AGENTS.md "Project decisions" and ipal-doctor.json, local .env with a fresh PAYLOAD_SECRET, install from the shipped lockfile, ipal-skills, ipal-tokens, generate:types/importmap, typecheck, ipal-doctor when shipped, secret check, first commit - @intecion/ipal-kit/starter: the building blocks (renderSite, validateAnswers, applyVariants, collectBundle, lockfileWithoutPlugin, secretFindings …) - build:starter packs reference/ into dist/starter/template.json.gz (90 KB); starter:gate in prepublishOnly: site from the packed tarball, frozen install, seed, build, targeted SEED_ONLY seed in production mode, full seed refused, pnpm start checks - D15: plugin dependencies pinned exactly (nodemailer 10.3.1) - reference/: @starter:if markers (runs as before), manifest generate/variants/rewrite - docs: project-starter.md, AGENT.md, ipal-setup, ipal-site, ipal-reference (+ api.md), README, PROGRAMISTA §2, CHANGELOG, docs/README, reference index Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
154049662e
commit
804a09efed
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* The architecture questions (AGENT.md "Ask before you build", ipal-setup stage 0) as data:
|
||||
* the shape of `--answers <file.json>`, validation, and the flags the answers turn on.
|
||||
* Nothing here has a silent default — a missing answer is an error the owner must fill in.
|
||||
*/
|
||||
import type { StarterFlags } from './text.js'
|
||||
|
||||
export type AnalyticsTool = 'clarity' | 'ga4' | 'gtm' | 'linkedIn' | 'metaPixel' | 'tiktok'
|
||||
export type ContentCollection = 'caseStudies' | 'posts'
|
||||
|
||||
export type StarterAnswers = {
|
||||
admin: {
|
||||
adminMeta: boolean
|
||||
/** Required when `adminMeta` is false — goes to ipal-doctor.json and "Project decisions". */
|
||||
adminMetaOffReason?: string
|
||||
agency: 'intecion' | 'none' | { name: string; url: string }
|
||||
twoFactor: boolean
|
||||
twoFactorOffReason?: string
|
||||
whiteLabel: boolean
|
||||
}
|
||||
consent: {
|
||||
banner: 'detailed' | 'inline' | 'modal'
|
||||
consentMode: 'advanced' | 'basic'
|
||||
cookieScanner: boolean
|
||||
cookieScannerOffReason?: string
|
||||
/** Browser crawl through the shared cookie-crawler service (needs IPAL_COOKIE_SCAN_* in Coolify). */
|
||||
crawl: boolean
|
||||
tools: AnalyticsTool[]
|
||||
}
|
||||
content: {
|
||||
collections: ContentCollection[]
|
||||
/** The site map in the owner's words, one line per page. */
|
||||
pages: string[]
|
||||
}
|
||||
forms: {
|
||||
list: string[]
|
||||
/** Inbox that receives submissions (Company → E-mail). */
|
||||
recipient: string
|
||||
transport: 'graph' | 'smtp'
|
||||
}
|
||||
hosting: {
|
||||
/** Which host the site answers on; the other one redirects. */
|
||||
canonical: 'apex' | 'www'
|
||||
/** Coolify server / project, free text. */
|
||||
coolify: string
|
||||
dns: string
|
||||
}
|
||||
industry: string
|
||||
languages: {
|
||||
default: string
|
||||
locales: { code: string; label: string }[]
|
||||
}
|
||||
market: string
|
||||
media: 'local' | 'r2'
|
||||
seo: {
|
||||
aiBots: 'allow' | 'block-training' | 'disallow'
|
||||
aiBotsReason?: string
|
||||
localBusiness: { type: string } | false
|
||||
}
|
||||
siteName: string
|
||||
styling: {
|
||||
accent?: string
|
||||
defaultTheme: 'dark' | 'light' | 'system'
|
||||
fluid: 'standard' | 'wide'
|
||||
fontBody: string
|
||||
fontHeading: string
|
||||
primary: string
|
||||
radius: 'round' | 'sharp' | 'soft'
|
||||
secondary?: string
|
||||
theme: 'both' | 'dark' | 'light'
|
||||
}
|
||||
tooling: { external: string[] }
|
||||
}
|
||||
|
||||
/** One prompt per architecture topic, in the order of AGENT.md "Ask before you build". */
|
||||
export const STARTER_TOPICS = [
|
||||
'siteName', 'market', 'industry', 'languages', 'styling', 'content', 'forms', 'consent', 'seo', 'media', 'admin', 'hosting', 'tooling',
|
||||
] as const
|
||||
|
||||
const LOCALE = /^[a-z]{2}(?:-[A-Z]{2})?$/
|
||||
const EMAIL = /^[^\s@,;]+@[^\s,;@][^\s,.;@]*\.[^\s,;@]+$/
|
||||
const TOOLS: AnalyticsTool[] = ['clarity', 'ga4', 'gtm', 'linkedIn', 'metaPixel', 'tiktok']
|
||||
|
||||
const isText = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0
|
||||
const oneOf = <T extends string>(v: unknown, list: readonly T[]): v is T => typeof v === 'string' && (list as readonly string[]).includes(v)
|
||||
|
||||
/**
|
||||
* Every problem with the answers, as readable lines (empty = valid). Limits of this version are
|
||||
* errors too, so the generator never writes a site the reference cannot back.
|
||||
*/
|
||||
export function validateAnswers(input: unknown): string[] {
|
||||
const a = (input ?? {}) as Partial<StarterAnswers>
|
||||
const errors: string[] = []
|
||||
const need = (ok: boolean, message: string) => {if (!ok) {errors.push(message)}}
|
||||
|
||||
need(isText(a.siteName), 'siteName: the site / company name (also the 2FA issuer)')
|
||||
need(isText(a.market), 'market: e.g. PL, UK, AU')
|
||||
need(isText(a.industry), 'industry: one line, e.g. "architecture studio"')
|
||||
|
||||
const langs = a.languages
|
||||
const codes = Array.isArray(langs?.locales) ? langs.locales.map((l) => l?.code) : []
|
||||
need(codes.length > 0 && codes.every((c) => typeof c === 'string' && LOCALE.test(c)), 'languages.locales: [{ code: "pl", label: "Polski" }, …]')
|
||||
need(Array.isArray(langs?.locales) && langs.locales.every((l) => isText(l?.label)), 'languages.locales: every locale needs a label')
|
||||
need(new Set(codes).size === codes.length, 'languages.locales: a code is listed twice')
|
||||
// The base seed writes Polish and English text and Polish default-locale slugs (reference/src/seed/base.ts).
|
||||
need(langs?.default === 'pl' && codes.includes('en'), 'languages: this version needs default "pl" and "en" among the locales (the base seed is Polish + English); other sites → the manual ipal-setup path')
|
||||
|
||||
const st = a.styling
|
||||
need(isText(st?.primary), 'styling.primary: the brand colour (any CSS colour, oklch recommended)')
|
||||
need(isText(st?.fontBody) && isText(st?.fontHeading), 'styling.fontBody / fontHeading: Google font names, e.g. "Inter"')
|
||||
need(oneOf(st?.theme, ['both', 'dark', 'light'] as const), 'styling.theme: light | dark | both')
|
||||
need(oneOf(st?.defaultTheme, ['dark', 'light', 'system'] as const), 'styling.defaultTheme: light | dark | system')
|
||||
need(st?.theme !== 'light' || st.defaultTheme === 'light', 'styling: a light-only site has defaultTheme "light"')
|
||||
need(st?.theme !== 'dark' || st.defaultTheme === 'dark', 'styling: a dark-only site has defaultTheme "dark"')
|
||||
need(oneOf(st?.radius, ['round', 'sharp', 'soft'] as const), 'styling.radius: sharp | soft | round')
|
||||
need(oneOf(st?.fluid, ['standard', 'wide'] as const), 'styling.fluid: standard (to 1280px) | wide (to 1920px)')
|
||||
|
||||
need(Array.isArray(a.content?.pages) && a.content.pages.length > 0, 'content.pages: the site map, one entry per page')
|
||||
need(Array.isArray(a.content?.collections) && a.content.collections.every((c) => oneOf(c, ['caseStudies', 'posts'] as const)), 'content.collections: [] or any of "posts", "caseStudies"')
|
||||
|
||||
need(Array.isArray(a.forms?.list), 'forms.list: the forms, e.g. ["Contact form"]')
|
||||
need(isText(a.forms?.recipient) && EMAIL.test(a.forms.recipient), 'forms.recipient: the inbox that receives submissions')
|
||||
need(oneOf(a.forms?.transport, ['graph', 'smtp'] as const), 'forms.transport: smtp | graph')
|
||||
|
||||
const c = a.consent
|
||||
need(Array.isArray(c?.tools) && c.tools.every((t) => oneOf(t, TOOLS)), `consent.tools: any of ${TOOLS.join(', ')} (or [])`)
|
||||
need(oneOf(c?.consentMode, ['advanced', 'basic'] as const), 'consent.consentMode: advanced | basic')
|
||||
need(oneOf(c?.banner, ['detailed', 'inline', 'modal'] as const), 'consent.banner: inline | modal | detailed')
|
||||
need(typeof c?.cookieScanner === 'boolean', 'consent.cookieScanner: true | false')
|
||||
need(c?.cookieScanner !== false || isText(c.cookieScannerOffReason), 'consent.cookieScannerOffReason: the owner\'s reason for turning the scanner off')
|
||||
need(typeof c?.crawl === 'boolean', 'consent.crawl: true | false')
|
||||
need(!c?.crawl || c.cookieScanner === true, 'consent.crawl needs consent.cookieScanner')
|
||||
|
||||
const seo = a.seo
|
||||
need(oneOf(seo?.aiBots, ['allow', 'block-training', 'disallow'] as const), 'seo.aiBots: allow | block-training | disallow')
|
||||
need(seo?.aiBots === 'allow' || isText(seo?.aiBotsReason), 'seo.aiBotsReason: the client decision behind blocking AI bots')
|
||||
need(seo?.localBusiness === false || isText(seo?.localBusiness?.type), 'seo.localBusiness: false or { type: "ProfessionalService" }')
|
||||
|
||||
need(oneOf(a.media, ['local', 'r2'] as const), 'media: r2 | local')
|
||||
|
||||
const ad = a.admin
|
||||
need(typeof ad?.twoFactor === 'boolean', 'admin.twoFactor: true | false')
|
||||
need(ad?.twoFactor !== false || isText(ad.twoFactorOffReason), 'admin.twoFactorOffReason: the owner\'s reason for turning 2FA off')
|
||||
need(typeof ad?.whiteLabel === 'boolean', 'admin.whiteLabel: true | false')
|
||||
need(typeof ad?.adminMeta === 'boolean', 'admin.adminMeta: true | false')
|
||||
need(ad?.adminMeta !== false || isText(ad.adminMetaOffReason), 'admin.adminMetaOffReason: the owner\'s reason')
|
||||
const agency = ad?.agency
|
||||
need(agency === 'intecion' || agency === 'none' || (typeof agency === 'object' && isText(agency.name) && /^https:\/\//.test(agency.url)), 'admin.agency: "intecion" | "none" | { name, url: "https://…" }')
|
||||
|
||||
need(oneOf(a.hosting?.canonical, ['apex', 'www'] as const), 'hosting.canonical: apex | www')
|
||||
need(isText(a.hosting?.coolify), 'hosting.coolify: the Coolify server / project')
|
||||
need(isText(a.hosting?.dns), 'hosting.dns: who adds the DNS records')
|
||||
|
||||
need(Array.isArray(a.tooling?.external), 'tooling.external: [] or the ext-* skills to install')
|
||||
return errors
|
||||
}
|
||||
|
||||
/** The feature flags the reference site's `@starter:if` markers test. */
|
||||
export function flagsFromAnswers(a: StarterAnswers): StarterFlags {
|
||||
const tools = new Set(a.consent.tools)
|
||||
return {
|
||||
adminMeta: a.admin.adminMeta,
|
||||
agencyCustom: typeof a.admin.agency === 'object',
|
||||
agencyNone: a.admin.agency === 'none',
|
||||
aiBotsBlockTraining: a.seo.aiBots === 'block-training',
|
||||
aiBotsDisallow: a.seo.aiBots === 'disallow',
|
||||
analytics: tools.has('ga4') || tools.has('gtm'),
|
||||
bannerDetailed: a.consent.banner === 'detailed',
|
||||
bannerInline: a.consent.banner === 'inline',
|
||||
bannerModal: a.consent.banner === 'modal',
|
||||
caseStudies: a.content.collections.includes('caseStudies'),
|
||||
clarity: tools.has('clarity'),
|
||||
collections: a.content.collections.length > 0,
|
||||
consentBasic: a.consent.consentMode === 'basic',
|
||||
cookieScanner: a.consent.cookieScanner,
|
||||
crawl: a.consent.crawl,
|
||||
defaultDark: a.styling.defaultTheme === 'dark',
|
||||
defaultLight: a.styling.defaultTheme === 'light',
|
||||
defaultSystem: a.styling.defaultTheme === 'system',
|
||||
// the reference site's own demo content, smoke tests and showcase — never in a new site
|
||||
demo: false,
|
||||
enforceCsp: false, // new sites start report-only (security.md → ROLL OUT CSP)
|
||||
graph: a.forms.transport === 'graph',
|
||||
linkedIn: tools.has('linkedIn'),
|
||||
localBusiness: a.seo.localBusiness !== false,
|
||||
metaPixel: tools.has('metaPixel'),
|
||||
posts: a.content.collections.includes('posts'),
|
||||
r2: a.media === 'r2',
|
||||
scannerWithoutCrawl: a.consent.cookieScanner && !a.consent.crawl,
|
||||
themeToggle: a.styling.theme === 'both',
|
||||
tiktok: tools.has('tiktok'),
|
||||
twoFactor: a.admin.twoFactor,
|
||||
whiteLabel: a.admin.whiteLabel,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* The starter bundle: the reference site's kept files plus its manifest and lockfile, in one gzipped
|
||||
* JSON file shipped in the plugin tarball (`dist/starter/template.json.gz`). Built at release time
|
||||
* (`pnpm build:starter`); a checkout of the repo can read `reference/` directly instead.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { join, relative, sep } from 'node:path'
|
||||
import { gunzipSync, gzipSync } from 'node:zlib'
|
||||
|
||||
import { lockfileWithoutPlugin } from './lockfile.js'
|
||||
import { assertManifest, fileRole, type StarterManifest } from './manifest.js'
|
||||
import { leftoverFakes, variantFlags } from './text.js'
|
||||
|
||||
export type StarterBundle = {
|
||||
/** path → content of every file the new site may get (kept, template and variant files). */
|
||||
files: Record<string, string>
|
||||
/** The reference lockfile without the plugin (lockfile.ts). */
|
||||
lockfile: string
|
||||
manifest: StarterManifest
|
||||
schema: 1
|
||||
}
|
||||
|
||||
const MANIFEST = 'starter.manifest.json'
|
||||
const LOCKFILE = 'pnpm-lock.yaml'
|
||||
|
||||
function walk(dir: string, root: string, out: string[]) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const full = join(dir, name)
|
||||
const rel = relative(root, full).split(sep).join('/')
|
||||
// never descend into installed or built trees
|
||||
if (name === 'node_modules' || name === '.next' || name === '.git') {continue}
|
||||
if (statSync(full).isDirectory()) {walk(full, root, out)}
|
||||
else {out.push(rel)}
|
||||
}
|
||||
}
|
||||
|
||||
/** Tracked files only when the folder is in a Git checkout (no local leftovers), else every file on disk. */
|
||||
function listFiles(dir: string): string[] {
|
||||
try {
|
||||
const out = execFileSync('git', ['ls-files', '-z', '--cached', '--', '.'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
|
||||
const tracked = out.split('\0').filter(Boolean)
|
||||
if (tracked.length) {return tracked.filter((path) => existsSync(join(dir, path)))}
|
||||
} catch {
|
||||
// not a Git checkout (e.g. an unpacked tarball) — fall back to the folder
|
||||
}
|
||||
const paths: string[] = []
|
||||
walk(dir, dir, paths)
|
||||
return paths
|
||||
}
|
||||
|
||||
/** Binary files are not part of the starter (media are seeded, never copied). */
|
||||
const isText = (content: Buffer) => !content.subarray(0, 8000).includes(0)
|
||||
|
||||
/**
|
||||
* Reads the reference site into a bundle. Fails when a kept file still holds a fake value
|
||||
* (it would leak "Example Studio" into a client site) or when a file is binary.
|
||||
*/
|
||||
export function collectBundle(referenceDir: string): StarterBundle {
|
||||
const manifestPath = join(referenceDir, MANIFEST)
|
||||
if (!existsSync(manifestPath)) {throw new Error(`no ${MANIFEST} in ${referenceDir}`)}
|
||||
const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
||||
assertManifest(manifest)
|
||||
const paths = listFiles(referenceDir)
|
||||
const files: Record<string, string> = {}
|
||||
const problems: string[] = []
|
||||
for (const path of paths.sort()) {
|
||||
if (path === MANIFEST || path === LOCKFILE) {continue}
|
||||
const role = fileRole(path, manifest)
|
||||
if (role === 'drop') {continue}
|
||||
const content = readFileSync(join(referenceDir, path))
|
||||
if (!isText(content)) {
|
||||
problems.push(`${path}: binary file — drop it in the manifest`)
|
||||
continue
|
||||
}
|
||||
const text = content.toString('utf8')
|
||||
if (role === 'keep') {
|
||||
// a kept file is copied as is, so it must not carry the reference company's values
|
||||
const fakes = leftoverFakes(text, manifest.placeholders)
|
||||
if (fakes.length) {problems.push(`${path}: kept as is but contains ${fakes.join(', ')} — list it under "template"`)}
|
||||
}
|
||||
files[path] = text
|
||||
}
|
||||
if (problems.length) {throw new Error(`starter bundle:\n ${problems.join('\n ')}`)}
|
||||
const lockPath = join(referenceDir, LOCKFILE)
|
||||
if (!existsSync(lockPath)) {throw new Error(`no ${LOCKFILE} in ${referenceDir}`)}
|
||||
return { files, lockfile: lockfileWithoutPlugin(readFileSync(lockPath, 'utf8')), manifest, schema: 1 }
|
||||
}
|
||||
|
||||
/** Every flag the bundle's markers and file variants use — the generator must set each one. */
|
||||
export function bundleFlags(bundle: StarterBundle): string[] {
|
||||
const flags = new Set<string>()
|
||||
for (const text of Object.values(bundle.files)) {for (const flag of variantFlags(text)) {flags.add(flag)}}
|
||||
for (const expr of Object.values(bundle.manifest.variants ?? {})) {flags.add(expr.replace(/^!/, ''))}
|
||||
return [...flags].sort()
|
||||
}
|
||||
|
||||
export function packBundle(bundle: StarterBundle): Buffer {
|
||||
return gzipSync(Buffer.from(JSON.stringify(bundle)), { level: 9 })
|
||||
}
|
||||
|
||||
export function unpackBundle(data: Buffer): StarterBundle {
|
||||
const bundle = JSON.parse(gunzipSync(data).toString('utf8')) as StarterBundle
|
||||
if (bundle.schema !== 1) {throw new Error('starter bundle: unknown schema — use the ipal-kit version that built it')}
|
||||
return bundle
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* `ipal-kit create <domain>` — a new client site from the reference site, following every team
|
||||
* convention (docs/project-starter.md). Run with `pnpm dlx @intecion/ipal-kit@<version> create <domain>`.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join, relative, resolve } from 'node:path'
|
||||
import { domainToASCII, fileURLToPath } from 'node:url'
|
||||
|
||||
import type { SiteContext } from './generate.js'
|
||||
|
||||
import { databaseNamesFor } from '../env/databaseName.js'
|
||||
import { type StarterAnswers, validateAnswers } from './answers.js'
|
||||
import { collectBundle, type StarterBundle, unpackBundle } from './bundle.js'
|
||||
import { askInTerminal } from './prompts.js'
|
||||
import { renderSite } from './render.js'
|
||||
import { secretFindings } from './secrets.js'
|
||||
|
||||
export const CREATE_USAGE = `Usage: ipal-kit create <domain> [options]
|
||||
pnpm dlx @intecion/ipal-kit@<version> create intecion.com
|
||||
|
||||
--dir <path> target folder (default ./<domain without dots>-web); must be new or empty
|
||||
--answers <file> the architecture answers as JSON (agents, CI) — no questions asked
|
||||
--external [a,b] also install the vendored ext-* skills (all, or the listed ones)
|
||||
--no-install write the files only; print the remaining steps
|
||||
--no-git no git init / first commit
|
||||
--dry-run print the decisions and the file list, write nothing
|
||||
--plugin-spec <spec> install @intecion/ipal-kit from this spec (release checks: a packed tarball)`
|
||||
|
||||
type Log = (line: string) => void
|
||||
|
||||
type CreateOptions = {
|
||||
answersFile?: string
|
||||
dir?: string
|
||||
domain: string
|
||||
dryRun: boolean
|
||||
external: null | string[]
|
||||
git: boolean
|
||||
install: boolean
|
||||
pluginSpec?: string
|
||||
}
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
// dist/modules/starter → package root
|
||||
const pkgRoot = resolve(here, '..', '..', '..')
|
||||
|
||||
function value(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name)
|
||||
if (i < 0) {return undefined}
|
||||
const next = args[i + 1]
|
||||
if (!next || next.startsWith('--')) {throw new Error(`${name} needs a value`)}
|
||||
return next
|
||||
}
|
||||
|
||||
export function parseCreateArgs(args: string[]): CreateOptions {
|
||||
const domain = args.find((arg, i) => !arg.startsWith('--') && !['--answers', '--dir', '--external', '--plugin-spec'].includes(args[i - 1] ?? ''))
|
||||
if (!domain) {throw new Error('the production domain is required, e.g. `ipal-kit create intecion.com`')}
|
||||
const ext = args.indexOf('--external')
|
||||
const extNext = ext >= 0 ? args[ext + 1] : undefined
|
||||
return {
|
||||
answersFile: value(args, '--answers'),
|
||||
dir: value(args, '--dir'),
|
||||
domain,
|
||||
dryRun: args.includes('--dry-run'),
|
||||
external: ext < 0 ? null : extNext && !extNext.startsWith('--') && extNext !== domain ? extNext.split(',').map((s) => s.trim()).filter(Boolean) : [],
|
||||
git: !args.includes('--no-git'),
|
||||
install: !args.includes('--no-install'),
|
||||
pluginSpec: value(args, '--plugin-spec'),
|
||||
}
|
||||
}
|
||||
|
||||
/** `https://www.Intecion.com/` → `intecion.com` (punycode for IDN); throws on anything that is not a domain. */
|
||||
export function normalizeDomain(input: string): string {
|
||||
const host = input.trim().toLowerCase().replace(/^[a-z][a-z\d+.-]*:\/\//, '').replace(/[/:?#].*$/, '').replace(/^www\./, '')
|
||||
const ascii = domainToASCII(host)
|
||||
if (!ascii || !/^(?:[a-z\d](?:[a-z\d-]*[a-z\d])?\.)+[a-z\d-]{2,}$/.test(ascii)) {throw new Error(`"${input}" is not a domain (e.g. intecion.com)`)}
|
||||
return ascii
|
||||
}
|
||||
|
||||
function loadBundle(): StarterBundle {
|
||||
const packed = join(pkgRoot, 'dist', 'starter', 'template.json.gz')
|
||||
if (existsSync(packed)) {return unpackBundle(readFileSync(packed))}
|
||||
// a checkout of the plugin repo: read the reference site directly
|
||||
const reference = join(pkgRoot, 'reference')
|
||||
if (existsSync(join(reference, 'starter.manifest.json'))) {return collectBundle(reference)}
|
||||
throw new Error('no starter templates in this ipal-kit (dist/starter/template.json.gz) — use a released version')
|
||||
}
|
||||
|
||||
function pluginVersion(): string {
|
||||
return (JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')) as { version: string }).version
|
||||
}
|
||||
|
||||
function run(log: Log, cwd: string, command: string, args: string[], env: Record<string, string> = {}): boolean {
|
||||
log(`$ ${[command, ...args].join(' ')}`)
|
||||
const result = spawnSync(command, args, { cwd, env: { ...process.env, ...env }, stdio: 'inherit' })
|
||||
return result.status === 0
|
||||
}
|
||||
|
||||
function writeFiles(dir: string, files: Record<string, string>) {
|
||||
for (const [path, content] of Object.entries(files)) {
|
||||
const target = join(dir, path)
|
||||
mkdirSync(dirname(target), { recursive: true })
|
||||
writeFileSync(target, content)
|
||||
}
|
||||
}
|
||||
|
||||
/** The local `.env`: `.env.example` with a fresh PAYLOAD_SECRET. Never committed (.gitignore). */
|
||||
export function localEnv(example: string): string {
|
||||
return example.replace(/^PAYLOAD_SECRET=.*$/m, `PAYLOAD_SECRET=${randomBytes(48).toString('base64url')}`)
|
||||
}
|
||||
|
||||
function committedFiles(dir: string): Record<string, string> {
|
||||
const listed = spawnSync('git', ['diff', '--cached', '--name-only', '-z'], { cwd: dir, encoding: 'utf8' }).stdout ?? ''
|
||||
const files: Record<string, string> = {}
|
||||
for (const path of listed.split('\0').filter(Boolean)) {files[path] = readFileSync(join(dir, path), 'utf8')}
|
||||
return files
|
||||
}
|
||||
|
||||
async function readAnswers(options: CreateOptions): Promise<StarterAnswers> {
|
||||
const answers = options.answersFile
|
||||
? (JSON.parse(readFileSync(resolve(options.answersFile), 'utf8')) as StarterAnswers)
|
||||
: await askInTerminal()
|
||||
if (options.external?.length && answers.tooling) {answers.tooling.external = options.external}
|
||||
return answers
|
||||
}
|
||||
|
||||
export async function runCreateCli(args: string[], log: Log = (line) => process.stdout.write(`${line}\n`)): Promise<number> {
|
||||
if (args.includes('--help') || args.includes('-h') || !args.length) {
|
||||
log(CREATE_USAGE)
|
||||
return args.length ? 0 : 1
|
||||
}
|
||||
let options: CreateOptions
|
||||
let domain: string
|
||||
try {
|
||||
options = parseCreateArgs(args)
|
||||
domain = normalizeDomain(options.domain)
|
||||
} catch (error) {
|
||||
log(`ipal-kit create: ${(error as Error).message}\n\n${CREATE_USAGE}`)
|
||||
return 1
|
||||
}
|
||||
const flat = domain.replace(/\./g, '')
|
||||
const cwd = process.cwd()
|
||||
const dir = resolve(options.dir ?? `${flat}-web`)
|
||||
if (existsSync(dir) && readdirSync(dir).length) {
|
||||
log(`ipal-kit create: ${dir} is not empty — pick a new folder with --dir`)
|
||||
return 1
|
||||
}
|
||||
if (!options.dir && existsSync(join(cwd, 'package.json'))) {
|
||||
log('ipal-kit create: this folder is a project — pass --dir ../<name>-web to create the site next to it')
|
||||
return 1
|
||||
}
|
||||
|
||||
const answers = await readAnswers(options)
|
||||
const errors = validateAnswers(answers)
|
||||
if (errors.length) {
|
||||
log(`ipal-kit create: the answers are incomplete — nothing was written:\n - ${errors.join('\n - ')}`)
|
||||
return 1
|
||||
}
|
||||
const ctx: SiteContext = {
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
dbNames: databaseNamesFor(domain),
|
||||
domain,
|
||||
pluginVersion: pluginVersion(),
|
||||
serverUrl: `https://${answers.hosting.canonical === 'www' ? 'www.' : ''}${domain}`,
|
||||
}
|
||||
let files: Record<string, string>
|
||||
try {
|
||||
files = renderSite(loadBundle(), answers, ctx)
|
||||
} catch (error) {
|
||||
log(`ipal-kit create: ${(error as Error).message}`)
|
||||
return 1
|
||||
}
|
||||
if (options.pluginSpec) {
|
||||
const pkg = JSON.parse(files['package.json'] ?? '{}') as { dependencies: Record<string, string> }
|
||||
pkg.dependencies['@intecion/ipal-kit'] = options.pluginSpec
|
||||
files['package.json'] = `${JSON.stringify(pkg, null, 2)}\n`
|
||||
}
|
||||
if (options.dryRun) {
|
||||
log(`Would create ${dir} (${Object.keys(files).length} files) for ${domain}:`)
|
||||
for (const path of Object.keys(files).sort()) {log(` ${path}`)}
|
||||
log(`\nDatabases: ${ctx.dbNames.dev} (local) / ${ctx.dbNames.prod} (Coolify)`)
|
||||
return 0
|
||||
}
|
||||
|
||||
writeFiles(dir, files)
|
||||
writeFileSync(join(dir, '.env'), localEnv(files['.env.example'] ?? ''))
|
||||
log(`Wrote ${Object.keys(files).length} files to ${relative(cwd, dir) || '.'}`)
|
||||
|
||||
const failed: string[] = []
|
||||
const step = (name: string, command: string, stepArgs: string[], env?: Record<string, string>) => {
|
||||
if (!run(log, dir, command, stepArgs, env)) {failed.push(name)}
|
||||
}
|
||||
if (options.install) {
|
||||
step('install', 'pnpm', ['install', '--ignore-workspace'])
|
||||
if (!failed.length) {
|
||||
step('skills', 'pnpm', ['exec', 'ipal-skills', ...(answers.tooling.external.length ? ['--external', answers.tooling.external.join(',')] : [])])
|
||||
step('tokens (contrast check)', 'pnpm', ['exec', 'ipal-tokens'])
|
||||
step('types', 'pnpm', ['generate:types'])
|
||||
step('import map', 'pnpm', ['generate:importmap'])
|
||||
step('typecheck', 'pnpm', ['typecheck'])
|
||||
if (existsSync(join(dir, 'node_modules', '.bin', 'ipal-doctor'))) {step('ipal-doctor', 'pnpm', ['exec', 'ipal-doctor', '--strict', '--offline'])}
|
||||
else {log('ipal-doctor is not in this ipal-kit version yet — run it once it ships.')}
|
||||
}
|
||||
}
|
||||
if (options.git && !failed.length) {
|
||||
step('git init', 'git', ['init', '-q', '-b', 'main'])
|
||||
step('git add', 'git', ['add', '-A'])
|
||||
const findings = secretFindings(committedFiles(dir))
|
||||
if (findings.length) {
|
||||
log(`Not committed — possible secrets:\n ${findings.join('\n ')}`)
|
||||
failed.push('secret check')
|
||||
} else {
|
||||
step('first commit', 'git', ['commit', '-q', '-m', `chore: create site with ipal-kit create ${ctx.pluginVersion}`])
|
||||
}
|
||||
}
|
||||
log(report(answers, ctx, dir, options, failed))
|
||||
return failed.length ? 1 : 0
|
||||
}
|
||||
|
||||
function report(a: StarterAnswers, ctx: SiteContext, dir: string, options: CreateOptions, failed: string[]): string {
|
||||
const lines = [
|
||||
'',
|
||||
failed.length ? `Created with problems in: ${failed.join(', ')} — fix them, then rerun the step.` : `Created ${ctx.domain} in ${dir}.`,
|
||||
'',
|
||||
'Next:',
|
||||
...(options.install ? [] : [' pnpm install && pnpm exec ipal-skills && pnpm exec ipal-tokens && pnpm generate:types && pnpm generate:importmap']),
|
||||
` 1. Local MongoDB with the database ${ctx.dbNames.dev} (DATABASE_URI in .env), then: pnpm dev`,
|
||||
` 2. pnpm seed (system pages, navigation, the forms to ${a.forms.recipient} — before launch only), then /admin → first user + 2FA`,
|
||||
' 3. Panel steps and the full checklist: .agents/skills/ipal-setup/SKILL.md §11; architecture answers: AGENTS.md',
|
||||
` 4. Deploy: docs/DEPLOY.md — Coolify app from the repo, MongoDB resource ${ctx.dbNames.prod}, DNS records for ${ctx.domain}`,
|
||||
...(a.consent.crawl ? [' 5. Coolify env: IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN (shared cookie-crawler)'] : []),
|
||||
]
|
||||
return lines.join('\n')
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/** ipal-doctor.json: the domain, not launched yet, and every deliberate difference silenced with its reason. */
|
||||
export function renderDoctorConfig(a: StarterAnswers, ctx: SiteContext): string {
|
||||
const until = new Date(`${ctx.date}T00:00:00Z`)
|
||||
until.setUTCDate(until.getUTCDate() + 28)
|
||||
const rules: Record<string, { off: true; reason: string; until?: string }> = {
|
||||
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`
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The lockfile a new site starts from: the reference site's `pnpm-lock.yaml` (lockfile v9) without
|
||||
* `@intecion/ipal-kit` itself. The reference links the plugin from the repo (`file:..`), and the
|
||||
* released tarball's integrity hash does not exist while that tarball is being built. So the starter
|
||||
* ships every other package locked; `pnpm install` keeps those entries and resolves only the plugin
|
||||
* (an exact version in package.json, whose own dependencies are exact too — D15).
|
||||
*/
|
||||
const PLUGIN = '@intecion/ipal-kit'
|
||||
|
||||
const indentOf = (line: string) => line.length - line.trimStart().length
|
||||
|
||||
/** The key of a YAML map line: `'@scope/name@file:..(x)':` → `@scope/name@file:..(x)`, `name:` → `name`. */
|
||||
function keyOf(line: string): string {
|
||||
const text = line.trim()
|
||||
if (text.startsWith("'")) {return text.slice(1, text.indexOf("'", 1))}
|
||||
return text.replace(/:.*$/, '')
|
||||
}
|
||||
|
||||
/** Removes every map entry at `indent` whose key `isTarget` accepts, with its nested lines. */
|
||||
function dropEntries(lines: string[], indent: number, isTarget: (key: string) => boolean): string[] {
|
||||
const out: string[] = []
|
||||
let skipping = false
|
||||
for (const line of lines) {
|
||||
const blank = line.trim() === ''
|
||||
if (skipping) {
|
||||
if (blank || indentOf(line) > indent) {continue}
|
||||
skipping = false
|
||||
}
|
||||
if (!blank && indentOf(line) === indent) {
|
||||
if (isTarget(keyOf(line))) {
|
||||
skipping = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
out.push(line)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference lockfile without the plugin: its importer entry and `dependenciesMeta`
|
||||
* (`injected`), and its `packages` / `snapshots` entries. Everything else is untouched.
|
||||
*/
|
||||
export function lockfileWithoutPlugin(lock: string): string {
|
||||
if (!/^lockfileVersion: '9\.\d'/m.test(lock)) {throw new Error('starter lockfile: expected pnpm lockfile v9')}
|
||||
let lines = lock.split('\n')
|
||||
// importers → . → dependencies → '@intecion/ipal-kit' (6 spaces), and dependenciesMeta of it
|
||||
lines = dropEntries(lines, 6, (key) => key === PLUGIN)
|
||||
lines = dropEntries(lines, 4, (key) => key === 'dependenciesMeta')
|
||||
// packages: / snapshots: entries (2 spaces), e.g. '@intecion/ipal-kit@file:..(hash)'
|
||||
lines = dropEntries(lines, 2, (key) => key.startsWith(`${PLUGIN}@`))
|
||||
const result = lines.join('\n').replace(/\n{3,}/g, '\n\n')
|
||||
if (result.includes(`${PLUGIN}@`) || result.includes(`'${PLUGIN}':`)) {throw new Error('starter lockfile: the plugin is still referenced')}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* `reference/starter.manifest.json` — how the reference site becomes a new project.
|
||||
* The reference site owns this file; the starter only reads it.
|
||||
*/
|
||||
export type StarterManifest = {
|
||||
/** Paths left out of the new site (globs, relative to reference/). */
|
||||
drop: string[]
|
||||
/** Files the starter writes itself from the answers instead of copying them (e.g. `src/i18n.config.ts`). */
|
||||
generate?: string[]
|
||||
keep: string[]
|
||||
/** token → the reference site's fake value, e.g. `{{domain}}` → `example-studio.pl`. */
|
||||
placeholders: Record<string, string>
|
||||
rewrite?: {
|
||||
'package.json'?: Record<string, null | string>
|
||||
}
|
||||
schema: number
|
||||
/** Files copied with the placeholders replaced. */
|
||||
template: string[]
|
||||
/** Whole files that exist only with a flag on, e.g. `{ "src/collections/Posts.ts": "posts" }` (`!flag` allowed). */
|
||||
variants?: Record<string, string>
|
||||
}
|
||||
|
||||
/** Paths every bundle skips, whatever the manifest says (installed, built or local-only files). */
|
||||
export const ALWAYS_SKIPPED = ['node_modules/**', '.next/**', '.env', '.env.local', '**/.DS_Store', '*.tsbuildinfo']
|
||||
|
||||
function globToRegExp(glob: string): RegExp {
|
||||
let source = ''
|
||||
for (let i = 0; i < glob.length; i++) {
|
||||
const char = glob[i]
|
||||
if (char === '*' && glob[i + 1] === '*') {
|
||||
// `**/` matches zero or more folders; a trailing `**` matches everything below
|
||||
source += glob[i + 2] === '/' ? '(?:.*/)?' : '.*'
|
||||
i += glob[i + 2] === '/' ? 2 : 1
|
||||
} else if (char === '*') {
|
||||
source += '[^/]*'
|
||||
} else if (char === '?') {
|
||||
source += '[^/]'
|
||||
} else {
|
||||
source += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${source}$`)
|
||||
}
|
||||
|
||||
/** Glob match on a `/`-separated relative path: `*`, `**`, `?`. */
|
||||
export function matchGlob(path: string, glob: string): boolean {
|
||||
return globToRegExp(glob).test(path)
|
||||
}
|
||||
|
||||
export type FileRole = 'drop' | 'generate' | 'keep' | 'template'
|
||||
|
||||
/** What happens to one path: drop wins, then generate, then template, then keep. */
|
||||
export function fileRole(path: string, manifest: StarterManifest): FileRole {
|
||||
const any = (globs: string[] | undefined) => (globs ?? []).some((glob) => matchGlob(path, glob))
|
||||
if (any(ALWAYS_SKIPPED) || any(manifest.drop)) {return 'drop'}
|
||||
if (any(manifest.generate)) {return 'generate'}
|
||||
if (any(manifest.template)) {return 'template'}
|
||||
return any(manifest.keep) ? 'keep' : 'drop'
|
||||
}
|
||||
|
||||
/** Checks the manifest's shape before anything is built from it. */
|
||||
export function assertManifest(value: unknown): asserts value is StarterManifest {
|
||||
const m = value as null | Partial<StarterManifest>
|
||||
const problems: string[] = []
|
||||
if (!m || typeof m !== 'object') {throw new Error('starter.manifest.json: not an object')}
|
||||
if (m.schema !== 1) {problems.push(`schema ${String(m.schema)} (this ipal-kit reads schema 1)`)}
|
||||
for (const key of ['drop', 'keep', 'template'] as const) {
|
||||
if (!Array.isArray(m[key])) {problems.push(`"${key}" must be a list of globs`)}
|
||||
}
|
||||
if (!m.placeholders || typeof m.placeholders !== 'object') {problems.push('"placeholders" must map {{token}} → fake value')}
|
||||
if (problems.length) {throw new Error(`starter.manifest.json: ${problems.join('; ')}`)}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* The architecture questions asked in the terminal, all before a single file is written.
|
||||
* Enter takes the shown recommendation — an explicit choice, recorded as the owner's answer.
|
||||
* Agents pass the same answers as JSON with `--answers` instead.
|
||||
*/
|
||||
import { createInterface } from 'node:readline/promises'
|
||||
|
||||
import type { AnalyticsTool, ContentCollection, StarterAnswers } from './answers.js'
|
||||
|
||||
type Ask = (question: string) => Promise<string>
|
||||
|
||||
function asker(ask: Ask) {
|
||||
const text = async (question: string, recommended?: string): Promise<string> => {
|
||||
for (;;) {
|
||||
const answer = (await ask(`${question}${recommended ? ` [${recommended}]` : ''}: `)).trim()
|
||||
if (answer) {return answer}
|
||||
if (recommended !== undefined) {return recommended}
|
||||
}
|
||||
}
|
||||
const choice = async <T extends string>(question: string, options: readonly T[], recommended: T): Promise<T> => {
|
||||
for (;;) {
|
||||
const answer = await text(`${question} (${options.join(' / ')})`, recommended)
|
||||
if ((options as readonly string[]).includes(answer)) {return answer as T}
|
||||
}
|
||||
}
|
||||
const yes = async (question: string, recommended: boolean) => (await choice(question, ['yes', 'no'] as const, recommended ? 'yes' : 'no')) === 'yes'
|
||||
const list = async (question: string, recommended: string): Promise<string[]> =>
|
||||
(await text(`${question} (comma-separated, "none" for none)`, recommended)).split(',').map((s) => s.trim()).filter((s) => s && s !== 'none')
|
||||
return { choice, list, text, yes }
|
||||
}
|
||||
|
||||
/** Asks every topic of AGENT.md "Ask before you build" and returns the answers (not yet validated). */
|
||||
export async function askAnswers(ask: Ask): Promise<StarterAnswers> {
|
||||
const { choice, list, text, yes } = asker(ask)
|
||||
const siteName = await text('1. Site / company name (also the 2FA issuer)')
|
||||
const market = await text(' Market', 'PL')
|
||||
const industry = await text(' Industry, one line')
|
||||
const extra = await list('2. Languages besides pl (default) and en, as code:Label', 'none')
|
||||
const locales = [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }, ...extra.map((e) => {
|
||||
const [code = '', label = code] = e.split(':').map((s) => s.trim())
|
||||
return { code, label }
|
||||
})]
|
||||
const primary = await text('3. Brand primary colour (any CSS colour)')
|
||||
const secondary = await text(' Secondary colour ("none")', 'none')
|
||||
const accent = await text(' Accent colour ("none")', 'none')
|
||||
const fontBody = await text(' Body font (Google font name)', 'Inter')
|
||||
const fontHeading = await text(' Heading font (Google font name)', fontBody)
|
||||
const theme = await choice(' Theme', ['both', 'light', 'dark'] as const, 'both')
|
||||
const defaultTheme = theme === 'both' ? await choice(' Default theme', ['system', 'light', 'dark'] as const, 'system') : theme
|
||||
const radius = await choice(' Corner style', ['sharp', 'soft', 'round'] as const, 'soft')
|
||||
const fluid = await choice(' Scale (standard = to 1280px, wide = to 1920px)', ['wide', 'standard'] as const, 'wide')
|
||||
const pages = await list('4. Pages (site map)', 'Home, About, Services, Contact, Privacy policy, Cookie policy')
|
||||
const collections = (await list(' Collections with their own URLs: posts, caseStudies', 'none')) as ContentCollection[]
|
||||
const forms = await list('5. Forms', 'Contact form')
|
||||
const recipient = await text(' Inbox that receives submissions')
|
||||
const transport = await choice(' E-mail transport', ['smtp', 'graph'] as const, 'smtp')
|
||||
const tools = (await list('6. Analytics: ga4, gtm, metaPixel, linkedIn, tiktok, clarity', 'ga4')) as AnalyticsTool[]
|
||||
const consentMode = await choice(' Consent Mode', ['advanced', 'basic'] as const, 'advanced')
|
||||
const banner = await choice(' Cookie settings window', ['detailed', 'modal', 'inline'] as const, 'detailed')
|
||||
const cookieScanner = await yes(' Cookie scanner', true)
|
||||
const cookieScannerOffReason = cookieScanner ? undefined : await text(' Why off (owner\'s reason)')
|
||||
const crawl = cookieScanner ? await yes(' Browser crawl through the shared cookie-crawler service', true) : false
|
||||
const localBusiness = await yes('7. Local business (address, opening hours in JSON-LD)', true)
|
||||
const businessType = localBusiness ? await text(' schema.org type', 'ProfessionalService') : ''
|
||||
const aiBots = await choice(' AI crawlers', ['allow', 'block-training', 'disallow'] as const, 'allow')
|
||||
const aiBotsReason = aiBots === 'allow' ? undefined : await text(' Client decision behind it')
|
||||
const media = await choice('8. Media', ['r2', 'local'] as const, 'r2')
|
||||
const twoFactor = await yes('9. 2FA for the panel', true)
|
||||
const twoFactorOffReason = twoFactor ? undefined : await text(' Why off (owner\'s reason)')
|
||||
const whiteLabel = await yes(' White-label (client brand in the panel)', true)
|
||||
const agencyChoice = await choice(' Agency credit', ['intecion', 'none', 'other'] as const, 'intecion')
|
||||
const agency = agencyChoice === 'other' ? { name: await text(' Agency name'), url: await text(' Agency URL (https://…)') } : agencyChoice
|
||||
const adminMeta = await yes(' Panel link preview (adminMeta)', true)
|
||||
const adminMetaOffReason = adminMeta ? undefined : await text(' Why off (owner\'s reason)')
|
||||
const canonical = await choice('10. Canonical host', ['apex', 'www'] as const, 'apex')
|
||||
const coolify = await text(' Coolify server / project')
|
||||
const dns = await text(' Who adds the DNS records', 'the team')
|
||||
const external = await list('11. External skills (ext-react-best-practices, ext-composition-patterns, ext-accessibility, ext-frontend-design, ext-payload)', 'none')
|
||||
const optional = (value: string) => (value === 'none' ? undefined : value)
|
||||
return {
|
||||
admin: { adminMeta, adminMetaOffReason, agency, twoFactor, twoFactorOffReason, whiteLabel },
|
||||
consent: { banner, consentMode, cookieScanner, cookieScannerOffReason, crawl, tools },
|
||||
content: { collections, pages },
|
||||
forms: { list: forms, recipient, transport },
|
||||
hosting: { canonical, coolify, dns },
|
||||
industry,
|
||||
languages: { default: 'pl', locales },
|
||||
market,
|
||||
media,
|
||||
seo: { aiBots, aiBotsReason, localBusiness: localBusiness ? { type: businessType } : false },
|
||||
siteName,
|
||||
styling: { accent: optional(accent), defaultTheme, fluid, fontBody, fontHeading, primary, radius, secondary: optional(secondary), theme },
|
||||
tooling: { external },
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the questions on stdin/stdout. */
|
||||
export async function askInTerminal(): Promise<StarterAnswers> {
|
||||
const rl = createInterface({ input: process.stdin, output: process.stdout })
|
||||
try {
|
||||
process.stdout.write('Architecture questions (AGENT.md "Ask before you build"). Enter = the recommendation in [brackets].\n\n')
|
||||
return await askAnswers((q) => rl.question(q))
|
||||
} finally {
|
||||
rl.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Turns the bundle and the owner's answers into the new site's files (path → content), in memory.
|
||||
* Pure: nothing is written here, so every rule is unit-testable.
|
||||
*/
|
||||
import { flagsFromAnswers, type StarterAnswers } from './answers.js'
|
||||
import { bundleFlags, type StarterBundle } from './bundle.js'
|
||||
import {
|
||||
renderAgentsMd,
|
||||
renderDesignMd,
|
||||
renderDoctorConfig,
|
||||
renderI18nConfig,
|
||||
renderTokens,
|
||||
rewriteFonts,
|
||||
rewritePackageJson,
|
||||
type SiteContext,
|
||||
} from './generate.js'
|
||||
import { fileRole } from './manifest.js'
|
||||
import { applyPlaceholders, applyVariants, leftoverFakes, type StarterFlags } from './text.js'
|
||||
|
||||
/** Files the starter writes from the answers; the manifest lists them under `generate`. */
|
||||
const GENERATORS: Record<string, (a: StarterAnswers, ctx: SiteContext) => string> = {
|
||||
'DESIGN.md': (a) => renderDesignMd(a),
|
||||
'ipal-doctor.json': renderDoctorConfig,
|
||||
'src/design/tokens.ts': (a) => renderTokens(a),
|
||||
'src/i18n.config.ts': (a) => renderI18nConfig(a),
|
||||
}
|
||||
|
||||
const LAYOUT = 'src/app/(frontend)/[locale]/layout.tsx'
|
||||
|
||||
/** The value of every placeholder token the starter knows. */
|
||||
export function placeholderValues(a: StarterAnswers, ctx: SiteContext): Record<string, string> {
|
||||
const flat = ctx.domain.replace(/\./g, '')
|
||||
const agency = typeof a.admin.agency === 'object' ? a.admin.agency : null
|
||||
return {
|
||||
'{{agencyName}}': agency?.name ?? '',
|
||||
'{{agencyUrl}}': agency?.url ?? '',
|
||||
'{{businessType}}': a.seo.localBusiness ? a.seo.localBusiness.type : 'Organization',
|
||||
'{{dbBase}}': ctx.dbNames.dev.replace(/_dev$/, ''),
|
||||
'{{domain}}': ctx.domain,
|
||||
'{{formRecipient}}': a.forms.recipient,
|
||||
'{{issuer}}': a.siteName,
|
||||
'{{mcpName}}': `${flat}-site`,
|
||||
'{{projectName}}': `${flat}-web`,
|
||||
'{{serverUrl}}': ctx.serverUrl,
|
||||
'{{siteName}}': a.siteName,
|
||||
}
|
||||
}
|
||||
|
||||
function isOn(expr: string, flags: StarterFlags): boolean {
|
||||
return expr.startsWith('!') ? flags[expr.slice(1)] !== true : flags[expr] === true
|
||||
}
|
||||
|
||||
export function renderSite(bundle: StarterBundle, a: StarterAnswers, ctx: SiteContext): Record<string, string> {
|
||||
const { manifest } = bundle
|
||||
const flags = flagsFromAnswers(a)
|
||||
const unknown = bundleFlags(bundle).filter((flag) => !(flag in flags))
|
||||
if (unknown.length) {throw new Error(`the reference site uses flags this ipal-kit does not set: ${unknown.join(', ')}`)}
|
||||
const values = placeholderValues(a, ctx)
|
||||
const missing = Object.keys(manifest.placeholders).filter((token) => !(token in values))
|
||||
if (missing.length) {throw new Error(`the manifest uses placeholders this ipal-kit does not fill: ${missing.join(', ')}`)}
|
||||
|
||||
// a fake value the site legitimately shares (e.g. the business type "ProfessionalService") is not a leftover
|
||||
const fakes = Object.fromEntries(Object.entries(manifest.placeholders).filter(([token, fake]) => !(values[token] ?? '').includes(fake)))
|
||||
const out: Record<string, string> = {}
|
||||
const problems: string[] = []
|
||||
for (const [path, source] of Object.entries(bundle.files)) {
|
||||
const role = fileRole(path, manifest)
|
||||
if (role === 'drop' || role === 'generate') {continue}
|
||||
const only = manifest.variants?.[path]
|
||||
if (only && !isOn(only, flags)) {continue}
|
||||
let text = applyVariants(source, flags, path)
|
||||
if (role === 'template') {text = applyPlaceholders(text, manifest.placeholders, values)}
|
||||
if (path === 'AGENTS.md') {text = renderAgentsMd(text, a, ctx)}
|
||||
if (path === 'package.json') {text = rewritePackageJson(text, manifest.rewrite?.['package.json'] ?? {}, ctx, a)}
|
||||
if (path === LAYOUT) {text = rewriteFonts(text, a)}
|
||||
const left = leftoverFakes(text, fakes)
|
||||
if (left.length) {problems.push(`${path}: still contains ${left.join(', ')}`)}
|
||||
out[path] = text
|
||||
}
|
||||
for (const path of manifest.generate ?? []) {
|
||||
const generate = GENERATORS[path]
|
||||
if (!generate) {
|
||||
problems.push(`${path}: listed under "generate" but this ipal-kit has no generator for it`)
|
||||
continue
|
||||
}
|
||||
out[path] = generate(a, ctx)
|
||||
}
|
||||
if (problems.length) {throw new Error(`rendering the site:\n ${problems.join('\n ')}`)}
|
||||
out['pnpm-lock.yaml'] = bundle.lockfile
|
||||
out['.ipal/starter.json'] = `${JSON.stringify({ answers: a, createdAt: ctx.date, domain: ctx.domain, ipalKit: ctx.pluginVersion }, null, 2)}\n`
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* The last check before the first commit: no `.env`, no assigned secret, no private key.
|
||||
* `.env.example` may hold names and public test values (Cloudflare's Turnstile test keys).
|
||||
*/
|
||||
// `NAME=value` where a `_`-separated part of NAME is SECRET / TOKEN / PASSWORD (or …_KEY after ACCESS / PRIVATE / SECRET),
|
||||
// and the value has 8+ characters and is not a placeholder (`<…>`, `[…]`, `${…}`, `…`). `TOKENS_BIN=` is not a secret.
|
||||
const ASSIGNMENT = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*['"]?(?![<[{$…]|\.\.\.)[^\s'"#]{8,}/gm
|
||||
const SECRET_NAME = /(?:^|_)(?:SECRET|TOKEN|PASSWORD|(?:ACCESS|PRIVATE|SECRET)_KEY)(?:_|$)/
|
||||
|
||||
function assignedSecret(text: string): null | string {
|
||||
for (const match of text.matchAll(ASSIGNMENT)) {
|
||||
if (SECRET_NAME.test(match[1] ?? '')) {return match[1] ?? null}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const PRIVATE_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY-----/
|
||||
|
||||
export function secretFindings(files: Record<string, string>): string[] {
|
||||
const findings: string[] = []
|
||||
for (const [path, text] of Object.entries(files)) {
|
||||
const name = path.split('/').pop() ?? path
|
||||
if (name === '.env' || (name.startsWith('.env.') && name !== '.env.example')) {
|
||||
findings.push(`${path}: env files with values are never committed`)
|
||||
continue
|
||||
}
|
||||
if (PRIVATE_KEY.test(text)) {findings.push(`${path}: contains a private key`)}
|
||||
const secret = name === '.env.example' ? null : assignedSecret(text)
|
||||
if (secret) {findings.push(`${path}: assigns a secret (${secret}=…)`)}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Text transforms the starter applies to reference files: in-file variants and placeholders.
|
||||
* Both are plain string work, so the reference site stays a normal, runnable project.
|
||||
*/
|
||||
|
||||
/** Feature flags of one generated site (`posts`, `twoFactor`, `crawl`, …). A missing flag is off. */
|
||||
export type StarterFlags = Record<string, boolean>
|
||||
|
||||
// A marker is a whole line: `// @starter:if x`, `{/* @starter:if !x */}`, `# @starter:if x`, `<!-- @starter:if x -->`.
|
||||
const MARKER = /^\s*(?:\/\/|#|\{\/\*|\/\*|<!--)\s*@starter:(if|else|endif)(?:\s+([!\w-]+))?\s*(?:(?:\*\/\}|\*\/|-->)\s*)?$/
|
||||
|
||||
/** `x` is on when the flag is true; `!x` when it is false. */
|
||||
function test(expr: string, flags: StarterFlags): boolean {
|
||||
const negate = expr.startsWith('!')
|
||||
const value = flags[negate ? expr.slice(1) : expr] === true
|
||||
return negate ? !value : value
|
||||
}
|
||||
|
||||
// An alternative the reference site does not run itself is written commented out: `//: code`, `#: KEY=`.
|
||||
const ALTERNATIVE = /^(\s*)(?:\/\/|#): ?/
|
||||
|
||||
/**
|
||||
* Keeps or removes the lines between `@starter:if <flag>` / `@starter:else` / `@starter:endif`
|
||||
* and removes the marker lines themselves. Blocks nest; a line stays when every enclosing block
|
||||
* keeps it. Inside kept blocks, `//: ` / `#: ` lines are uncommented — that is how the reference
|
||||
* site carries code it does not run itself (e.g. `twoFactor: false`). An unbalanced marker throws.
|
||||
*/
|
||||
export function applyVariants(text: string, flags: StarterFlags, file = 'file'): string {
|
||||
const out: string[] = []
|
||||
const stack: { keep: boolean; line: number; seenElse: boolean }[] = []
|
||||
text.split('\n').forEach((line, index) => {
|
||||
const match = MARKER.exec(line)
|
||||
if (!match) {
|
||||
if (!stack.length) {out.push(line)}
|
||||
else if (stack.every((block) => block.keep)) {out.push(line.replace(ALTERNATIVE, '$1'))}
|
||||
return
|
||||
}
|
||||
const [, kind, expr] = match
|
||||
const at = `${file}:${index + 1}`
|
||||
const top = stack[stack.length - 1]
|
||||
if (kind === 'if') {
|
||||
if (!expr) {throw new Error(`@starter:if without a flag at ${at}`)}
|
||||
stack.push({ keep: test(expr, flags), line: index + 1, seenElse: false })
|
||||
} else if (kind === 'else') {
|
||||
if (!top || top.seenElse) {throw new Error(`stray @starter:else at ${at}`)}
|
||||
top.keep = !top.keep
|
||||
top.seenElse = true
|
||||
} else {
|
||||
if (!top) {throw new Error(`stray @starter:endif at ${at}`)}
|
||||
stack.pop()
|
||||
}
|
||||
})
|
||||
const open = stack[stack.length - 1]
|
||||
if (open) {throw new Error(`@starter:if at ${file}:${open.line} has no @starter:endif`)}
|
||||
return out.join('\n')
|
||||
}
|
||||
|
||||
/** Every flag a text's markers mention (without `!`). */
|
||||
export function variantFlags(text: string): string[] {
|
||||
const found = new Set<string>()
|
||||
for (const line of text.split('\n')) {
|
||||
const match = MARKER.exec(line)
|
||||
if (match?.[1] === 'if' && match[2]) {found.add(match[2].replace(/^!/, ''))}
|
||||
}
|
||||
return [...found]
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces each fake value of the reference site with the new site's value.
|
||||
* `values` maps token → new value, `fakes` maps token → the reference's fake value.
|
||||
* Longest fake first, so `example-studiopl-web` wins over `example-studiopl`.
|
||||
*/
|
||||
export function applyPlaceholders(text: string, fakes: Record<string, string>, values: Record<string, string>): string {
|
||||
const pairs = Object.entries(fakes)
|
||||
.filter(([token]) => token in values)
|
||||
.sort(([, a], [, b]) => b.length - a.length)
|
||||
let result = text
|
||||
for (const [token, fake] of pairs) {result = result.split(fake).join(values[token] ?? fake)}
|
||||
return result
|
||||
}
|
||||
|
||||
/** The fake values still present in a text (the generator fails on any). */
|
||||
export function leftoverFakes(text: string, fakes: Record<string, string>): string[] {
|
||||
return [...new Set(Object.values(fakes))].filter((fake) => text.includes(fake))
|
||||
}
|
||||
Reference in New Issue
Block a user