Files
ipal-kit/test/starter.test.ts
T

307 lines
16 KiB
TypeScript

import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
applyPlaceholders,
applyVariants,
bundleFlags,
collectBundle,
fileRole,
flagsFromAnswers,
leftoverFakes,
localEnv,
lockfileWithoutPlugin,
matchGlob,
normalizeDomain,
packBundle,
parseCreateArgs,
renderDoctorConfig,
renderI18nConfig,
renderSite,
rewriteFonts,
runCreateCli,
secretFindings,
type SiteContext,
type StarterAnswers,
type StarterManifest,
unpackBundle,
validateAnswers,
} from '../src/exports/starter.js'
import { externalSkillNames, resolveExternal, writeFiles } from '../src/modules/starter/cli.js'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const reference = path.join(root, 'reference')
function answers(patch: (a: StarterAnswers) => void = () => {}): StarterAnswers {
const a: StarterAnswers = {
admin: { adminMeta: true, agency: 'intecion', twoFactor: true, whiteLabel: true },
consent: { banner: 'detailed', consentMode: 'advanced', cookieScanner: true, crawl: false, tools: ['ga4'] },
content: { collections: ['posts'], pages: ['Home', 'Contact'] },
forms: { list: ['Contact form'], recipient: '[email protected]', transport: 'smtp' },
hosting: { canonical: 'apex', coolify: 'coolify-1', dns: 'the team' },
industry: 'bakery',
languages: { default: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
market: 'PL',
media: 'r2',
seo: { aiBots: 'allow', localBusiness: { type: 'Bakery' } },
siteName: 'Acme Bakery',
styling: { defaultTheme: 'system', fluid: 'wide', fontBody: 'Inter', fontHeading: 'Space Grotesk', primary: 'oklch(0.5 0.17 30)', radius: 'soft', theme: 'both' },
tooling: { external: [] },
}
patch(a)
return a
}
const ctx: SiteContext = {
date: '2026-11-02',
dbNames: { dev: 'acme-testpl_dev', prod: 'acme-testpl_prod' },
domain: 'acme-test.pl',
pluginVersion: '1.15.0',
serverUrl: 'https://acme-test.pl',
}
describe('starter: variants', () => {
const flags = { a: true, b: false }
it('keeps or drops blocks, with else, negation and every comment style', () => {
const text = ['x', '// @starter:if a', 'A', '// @starter:else', 'notA', '// @starter:endif', '# @starter:if !b', 'notB', '# @starter:endif', '{/* @starter:if b */}', 'B', '{/* @starter:endif */}', '<!-- @starter:if a -->', 'mdA', '<!-- @starter:endif -->'].join('\n')
expect(applyVariants(text, flags)).toBe(['x', 'A', 'notB', 'mdA'].join('\n'))
})
it('uncomments `//: ` and `#: ` lines inside a kept block only, and nests', () => {
const text = ['// @starter:if !b', ' //: twoFactor: false,', ' #: GRAPH_SENDER=', ' // @starter:if a', ' //: inner: true,', ' // @starter:endif', '// @starter:endif', '//: outside stays a comment'].join('\n')
expect(applyVariants(text, flags)).toBe([' twoFactor: false,', ' GRAPH_SENDER=', ' inner: true,', '//: outside stays a comment'].join('\n'))
})
it('throws on unbalanced markers', () => {
expect(() => applyVariants('// @starter:if a\nx', flags, 'f.ts')).toThrow(/f\.ts:1 has no @starter:endif/)
expect(() => applyVariants('// @starter:endif', flags)).toThrow(/stray/)
expect(() => applyVariants('// @starter:if a\n// @starter:else\n// @starter:else\n// @starter:endif', flags)).toThrow(/stray @starter:else/)
})
})
describe('starter: placeholders and manifest', () => {
const fakes = { '{{dbBase}}': 'example-studiopl', '{{domain}}': 'example-studio.pl', '{{projectName}}': 'example-studiopl-web' }
it('replaces the longest fake first and reports leftovers', () => {
const text = 'example-studiopl-web example-studiopl_dev example-studio.pl'
expect(applyPlaceholders(text, fakes, { '{{dbBase}}': 'acme', '{{domain}}': 'acme.pl', '{{projectName}}': 'acmepl-web' })).toBe('acmepl-web acme_dev acme.pl')
expect(leftoverFakes('nothing here', fakes)).toEqual([])
expect(leftoverFakes('see example-studio.pl', fakes)).toEqual(['example-studio.pl'])
})
it('matches globs and resolves file roles (drop > generate > template > keep)', () => {
expect(matchGlob('e2e/smoke.spec.ts', 'e2e/**')).toBe(true)
expect(matchGlob('src/a/b.ts', 'src/*.ts')).toBe(false)
expect(matchGlob('x/.DS_Store', '**/.DS_Store')).toBe(true)
const manifest = { drop: ['e2e/**'], generate: ['DESIGN.md'], keep: ['**'], placeholders: {}, schema: 1, template: ['package.json'] } as StarterManifest
expect(fileRole('e2e/x.ts', manifest)).toBe('drop')
expect(fileRole('node_modules/x/index.js', manifest)).toBe('drop')
expect(fileRole('DESIGN.md', manifest)).toBe('generate')
expect(fileRole('package.json', manifest)).toBe('template')
expect(fileRole('src/proxy.ts', manifest)).toBe('keep')
})
})
describe('starter: answers', () => {
it('accepts a complete set and names every missing answer', () => {
expect(validateAnswers(answers())).toEqual([])
const errors = validateAnswers({})
expect(errors.length).toBeGreaterThan(15)
expect(errors.join('\n')).toMatch(/siteName/)
})
it('needs the owner\'s reason for every module turned off', () => {
const a = answers((x) => {
x.admin.twoFactor = false
x.consent.cookieScanner = false
x.seo.aiBots = 'disallow'
})
expect(validateAnswers(a).join('\n')).toMatch(/twoFactorOffReason[\s\S]*cookieScannerOffReason[\s\S]*aiBotsReason|twoFactorOffReason/)
expect(validateAnswers(a)).toHaveLength(3)
})
it('refuses single-language and English-default sites with a pointer to iapl-setup', () => {
const single = validateAnswers(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }] }))
expect(single).toHaveLength(1)
expect(single[0]).toMatch(/single-language site is not supported by `iapl create` yet .*iapl-setup/)
const english = validateAnswers(answers((x) => { x.languages.default = 'en' }))
expect(english).toHaveLength(1)
expect(english[0]).toMatch(/default language other than "pl" \(here "en"\).*iapl-setup/)
expect(validateAnswers(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }, { code: 'de', label: 'Deutsch' }] }))[0]).toMatch(/without "en"/)
expect(validateAnswers(answers((x) => { x.languages.locales.push({ code: 'de', label: 'Deutsch' }) }))).toEqual([])
})
it('stops the command before writing anything', async () => {
const lines: string[] = []
const dir = path.join(root, '.starter-test-single')
const file = path.join(root, '.starter-test-answers.json')
writeFileSync(file, JSON.stringify(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }] })))
try {
expect(await runCreateCli(['acme-test.pl', '--answers', file, '--dir', dir, '--no-install', '--no-git'], (line) => lines.push(line))).toBe(1)
expect(lines.join('\n')).toMatch(/nothing was written[\s\S]*single-language site[\s\S]*iapl-setup/)
expect(existsSync(dir)).toBe(false)
} finally {
rmSync(file, { force: true })
}
})
it('turns answers into the flags the reference markers test', () => {
const flags = flagsFromAnswers(answers((x) => { x.consent.tools = ['metaPixel'] }))
expect(flags).toMatchObject({ analytics: false, demo: false, enforceCsp: false, metaPixel: true, posts: true, scannerWithoutCrawl: true, twoFactor: true })
})
})
describe('starter: generated files', () => {
it('writes the languages, fonts and the doctor config', () => {
expect(renderI18nConfig(answers())).toContain("defaultLocale: 'pl'")
const layout = "import { Fraunces, Inter } from 'next/font/google'\nconst body = Inter({ x })\nconst heading = Fraunces({ y })"
expect(rewriteFonts(layout, answers())).toBe("import { Inter, Space_Grotesk } from 'next/font/google'\nconst body = Inter({ x })\nconst heading = Space_Grotesk({ y })")
const doctor = JSON.parse(renderDoctorConfig(answers((x) => {
x.admin.twoFactor = false
x.admin.twoFactorOffReason = 'SSO in front of the panel'
}), ctx)) as { rules: Record<string, { reason: string; until?: string }> }
expect(doctor.rules.csp?.until).toBe('2026-11-30')
expect(doctor.rules['2fa']?.reason).toBe('SSO in front of the panel')
})
it('removes the plugin from the lockfile and nothing else', () => {
const lock = [
"lockfileVersion: '9.0'", '', 'importers:', '', ' .:', ' dependencies:', " '@intecion/ipal-kit':", ' specifier: file:..', ' version: file:..(abc)',
' next:', ' specifier: 16.4.3', ' version: 16.4.3', ' dependenciesMeta:', " '@intecion/ipal-kit':", ' injected: true', '',
'packages:', '', " '@intecion/ipal-kit@file:..':", ' resolution: {directory: .., type: directory}', '', ' [email protected]:', ' resolution: {integrity: x}', '',
'snapshots:', '', " '@intecion/ipal-kit@file:..(abc)':", ' dependencies:', ' next: 16.4.3', '', ' [email protected]: {}', '',
].join('\n')
const out = lockfileWithoutPlugin(lock)
expect(out).not.toContain('ipal-kit')
expect(out).not.toContain('dependenciesMeta')
expect(out).toContain(" [email protected]:\n resolution: {integrity: x}")
expect(out).toContain(' [email protected]: {}')
})
it('finds secrets but not placeholders or the env example', () => {
expect(secretFindings({ '.env': 'X=1' })).toHaveLength(1)
expect(secretFindings({ 'src/a.ts': 'PAYLOAD_SECRET=abcdefghijklmnop' })).toHaveLength(1)
expect(secretFindings({ '.env.example': 'TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA', 'docs/x.md': 'PAYLOAD_SECRET=<random-string-min-32-chars>' })).toEqual([])
expect(localEnv('PAYLOAD_SECRET=\nX=1')).toMatch(/^PAYLOAD_SECRET=[\w-]{60,}\nX=1$/)
})
it('parses the command line and the domain', () => {
expect(normalizeDomain('https://www.Acme-Test.pl/')).toBe('acme-test.pl')
expect(() => normalizeDomain('localhost')).toThrow(/not a domain/)
expect(parseCreateArgs(['acme.pl', '--answers', 'a.json', '--external', '--no-git'])).toMatchObject({ answersFile: 'a.json', domain: 'acme.pl', external: [], git: false, install: true })
})
it('a bare --external means every external skill; a list stays as given', () => {
const all = externalSkillNames()
expect(all).toContain('ext-accessibility')
expect(resolveExternal([], () => all)).toEqual(all)
expect(resolveExternal(['ext-payload'])).toEqual(['ext-payload'])
expect(resolveExternal(null)).toBeNull()
})
})
describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('starter: the reference site', () => {
const bundle = collectBundle(reference)
it('round-trips through the packed bundle and uses only flags the starter sets', () => {
expect(unpackBundle(packBundle(bundle)).files).toEqual(bundle.files)
const known = Object.keys(flagsFromAnswers(answers()))
expect(bundleFlags(bundle).filter((flag) => !known.includes(flag))).toEqual([])
})
it('renders a site with no reference values, demo files or plugin link', () => {
const files = renderSite(bundle, answers(), ctx)
const all = Object.entries(files)
for (const [file, text] of all) {
expect(`${file}: ${/example-studio|Example Studio|E2E_ADMIN/.exec(text)?.[0] ?? ''}`).toBe(`${file}: `)
}
expect(Object.keys(files).some((f) => f.startsWith('e2e/') || f.endsWith('/demo.ts') || f.startsWith('.agents/'))).toBe(false)
const pkg = JSON.parse(files['package.json'] ?? '') as { dependencies: Record<string, string>; scripts: Record<string, string> }
expect(pkg.dependencies['@intecion/ipal-kit']).toBe('1.15.0')
expect(pkg.scripts['test:e2e']).toBeUndefined()
expect(files['next.config.ts']).toContain("mode: 'report-only'")
expect(files['src/payload.config.ts']).toContain("twoFactor: { issuer: 'Acme Bakery', plugin: payloadTotp }")
expect(files['src/payload.config.ts']).toContain('cookieScanner: true,')
expect(files['src/lib/content.ts']).toContain("type: 'Bakery'")
expect(files['.env.example']).toContain('DATABASE_URI=mongodb://127.0.0.1:27017/acme-testpl_dev')
expect(files['AGENTS.md']).toMatch(/## Project decisions\n- Languages: pl, en/)
expect(files['src/seed/base.ts']).toContain("email: '[email protected]'")
expect(files['pnpm-lock.yaml']).not.toContain('@intecion/ipal-kit')
const traced = renderSite(bundle, answers(), { ...ctx, source: { bundleSha256: 'abc', commit: 'def' } })
expect(JSON.parse(traced['.iapl/starter.json'] ?? '')).toMatchObject({ iapl: '1.15.0', source: { bundleSha256: 'abc', commit: 'def' } })
const doctor = JSON.parse(files['iapl-doctor.json'] ?? '') as { rules: Record<string, unknown> }
expect(Object.keys(doctor.rules).sort()).toEqual(['audit:collections-present', 'csp', 'i18n-literals'])
expect((JSON.parse(files['package.json'] ?? '') as { packageManager?: string }).packageManager).toMatch(/^pnpm@\d/)
})
it('drops what the owner turned off', () => {
const files = renderSite(bundle, answers((x) => {
x.admin.twoFactor = false
x.admin.twoFactorOffReason = 'SSO'
x.content.collections = []
x.media = 'local'
x.seo.localBusiness = false
}), ctx)
expect(files['src/collections/Posts.ts']).toBeUndefined()
expect(files['src/collections/entryFields.ts']).toBeUndefined()
expect(files['src/payload.config.ts']).toContain('twoFactor: false,')
expect(files['src/payload.config.ts']).not.toMatch(/payloadTotp|Posts/)
expect(files['src/blocks/configs.ts']).not.toContain('entryList')
expect(files['src/instrumentation.ts']).toContain('storage: false,')
expect(files['src/lib/content.ts']).not.toMatch(/buildLocalBusinessJsonLd|getPayload/)
expect(files['AGENTS.md']).toContain('iapl-audit-skip: twofactor, r2')
expect(Object.keys((JSON.parse(files['iapl-doctor.json'] ?? '') as { rules: object }).rules).sort()).toEqual(['2fa', 'csp', 'i18n-literals'])
expect(files['src/instrumentation.ts']).not.toContain('cookieCrawl')
})
})
describe('starter: links and paths (IAWL ideas 12, 13)', () => {
const site = () => {
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-starter-links-'))
const manifest: StarterManifest = { drop: [], keep: ['**'], placeholders: {}, schema: 1, template: [] }
writeFileSync(path.join(dir, 'starter.manifest.json'), JSON.stringify(manifest))
writeFileSync(path.join(dir, 'pnpm-lock.yaml'), "lockfileVersion: '9.0'\n")
writeFileSync(path.join(dir, 'kept.ts'), 'export const a = 1\n')
return dir
}
it('a symbolic link is refused: its target is never read into the published bundle', () => {
const dir = site()
const secret = path.join(dir, '..', `${path.basename(dir)}-secret.txt`)
writeFileSync(secret, 'PRIVATE KEY OF SOMEBODY ELSE')
symlinkSync(secret, path.join(dir, 'leak.txt'))
mkdirSync(path.join(dir, 'outside'))
symlinkSync(path.dirname(secret), path.join(dir, 'outside', 'up'))
try {
expect(() => collectBundle(dir)).toThrow(/leak\.txt: symbolic link/)
rmSync(path.join(dir, 'leak.txt'))
// a link to a folder is not walked into either
expect(() => collectBundle(dir)).toThrow(/outside\/up: symbolic link/)
rmSync(path.join(dir, 'outside'), { force: true, recursive: true })
expect(Object.keys(collectBundle(dir).files)).toEqual(['kept.ts'])
} finally {
rmSync(dir, { force: true, recursive: true })
rmSync(secret, { force: true })
}
})
it('a bundle path outside the new folder stops the run before anything is written', () => {
const parent = mkdtempSync(path.join(tmpdir(), 'iapl-starter-paths-'))
const dir = path.join(parent, 'site')
try {
for (const bad of ['../escaped.txt', 'a/../../escaped.txt', path.join(parent, 'abs.txt')]) {
expect(() => writeFiles(dir, { [bad]: 'no', 'ok.txt': 'fine' }), bad).toThrow(/outside the new folder/)
}
expect(readdirSync(parent)).toEqual([])
writeFiles(dir, { 'ok.txt': 'fine', 'src/a/b.ts': 'x' })
expect(readdirSync(dir).sort()).toEqual(['ok.txt', 'src'])
} finally {
rmSync(parent, { force: true, recursive: true })
}
})
})