Files
ipal-kit/scripts/starter-gate.mjs
T
Radosław SmolińskiandClaude Opus 5.5 7e1f09c95a starter:gate: the production full-seed check needs the guard's message; an early exit is retried
payload run can end with exit 0 and no output before Payload initializes (its bin does `void start()`;
when the script's top-level await is left without live handles, Node exits). Such a run proved nothing
but passed or failed the `refused !== 0` check at random. Now only "full seed refused" with a non-zero
exit counts; a run without "[ipal] Plugin initialized" is inconclusive and retried up to 3 times; all
three inconclusive fails the gate with that reason.

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

223 lines
12 KiB
JavaScript

#!/usr/bin/env node
// pnpm starter:gate — the release gate of `ipal-kit create` (prepublishOnly, after build:starter).
// Packs the plugin, creates a site from the PACKED tarball the way a developer does (pnpm dlx), then builds and
// runs it the way Coolify does: frozen install, `pnpm generate:types && pnpm build`, `pnpm start`, MongoDB in its
// own container. It runs the documented targeted seed in production mode, checks that a full seed is refused
// there, and runs `ipal-doctor --strict` when the plugin ships it. Any failure exits 1 and blocks the publish.
// pnpm starter:gate → everything, then cleans up (the work folder and the MongoDB container)
// pnpm starter:gate --keep → leave .starter-gate/ for inspection
// Needs Docker (MongoDB image mongo:7) and the npm registry (or a warm pnpm store). With the `nixpacks` CLI on
// PATH it also builds the site with Coolify's build pack and runs the seed inside that image.
import { spawn, spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
const keep = process.argv.includes('--keep')
// a short path inside the repo: pnpm's store index uses the tarball path in a file name (ENAMETOOLONG otherwise)
const work = join(root, '.starter-gate')
const domain = 'release-check.example'
const mongoName = `ipal-starter-gate-${process.pid}`
const PORT = '3311'
const results = []
let mongoStarted = false
let server = null
function log(line) {
console.log(`[starter:gate] ${line}`)
}
function sh(cwd, command, args, env = {}, { allowFail = false } = {}) {
log(`$ ${[command, ...args].join(' ')}`)
const result = spawnSync(command, args, { cwd, env: { ...process.env, ...env }, stdio: 'inherit' })
if (result.status !== 0 && !allowFail) {throw new Error(`${command} ${args.join(' ')} → exit ${result.status}`)}
return result.status ?? 1
}
function out(command, args) {
return spawnSync(command, args, { encoding: 'utf8' }).stdout?.trim() ?? ''
}
function check(name, ok, detail = '') {
results.push({ detail, name, ok })
log(`${ok ? '✓' : '✗'} ${name}${detail ? ` — ${detail}` : ''}`)
if (!ok) {throw new Error(`gate failed: ${name}`)}
}
/**
* Runs the production full seed and decides whether the guard refused it. Only the guard's own message counts:
* an exit code alone does not, because `payload run` can end with exit 0 and no output before Payload initializes
* (its bin does `void start()`; when the script's top-level `await getPayload()` is left with nothing that keeps the
* event loop alive, Node simply exits). Such a run says nothing — it is retried, up to `tries` times.
*/
function fullSeedRefused(site, env, tries = 3) {
for (let attempt = 1; attempt <= tries; attempt++) {
log(`$ pnpm seed (production, no SEED_ONLY) — attempt ${attempt}/${tries}`)
const run = spawnSync('pnpm', ['seed'], { cwd: site, encoding: 'utf8', env: { ...process.env, ...env } })
const output = `${run.stdout ?? ''}${run.stderr ?? ''}`
process.stdout.write(output)
if (/full seed refused/.test(output)) {return run.status !== 0}
if (/\[ipal\] Plugin initialized/.test(output)) {
log(`Payload initialized but the seed was not refused (exit ${run.status})`)
return false
}
log(`inconclusive: Payload never initialized (exit ${run.status}, ${output.trim() ? 'no guard message' : 'no output'})${attempt < tries ? ' — retrying' : ''}`)
}
throw new Error(`gate failed: the production full seed was inconclusive in all ${tries} runs — Payload never initialized, so the guard was never reached`)
}
async function waitFor(url, seconds) {
for (let i = 0; i < seconds; i++) {
try {
const res = await fetch(url)
if (res.status < 500) {return res.status}
} catch {
// not up yet
}
await new Promise((r) => setTimeout(r, 1000))
}
return 0
}
const answers = {
admin: { adminMeta: true, agency: 'intecion', twoFactor: true, whiteLabel: true },
consent: { banner: 'detailed', consentMode: 'advanced', cookieScanner: true, crawl: true, tools: ['ga4'] },
content: { collections: ['posts'], pages: ['Home', 'About', 'Services', 'Blog', 'Contact', 'Privacy policy', 'Cookie policy'] },
forms: { list: ['Contact form'], recipient: '[email protected]', transport: 'smtp' },
hosting: { canonical: 'apex', coolify: 'release gate', dns: 'the team' },
industry: 'release check',
languages: { default: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
market: 'PL',
media: 'r2',
seo: { aiBots: 'allow', localBusiness: { type: 'ProfessionalService' } },
siteName: 'Release Check',
styling: { defaultTheme: 'system', fluid: 'wide', fontBody: 'Inter', fontHeading: 'Inter', primary: 'oklch(0.5 0.17 250)', radius: 'soft', theme: 'both' },
tooling: { external: [] },
}
async function main() {
if (!existsSync(join(root, 'dist', 'starter', 'template.json.gz'))) {throw new Error('run `pnpm build && pnpm build:starter` first')}
rmSync(work, { force: true, recursive: true })
mkdirSync(work, { recursive: true })
// 1. the tarball exactly as it would be published — a new file name every run: pnpm's dlx cache is keyed by the
// spec, so a reused path would silently run the PREVIOUS run's plugin
sh(root, 'pnpm', ['pack', '--pack-destination', work])
const packed = readdirSync(work).find((f) => f.endsWith('.tgz'))
const tarball = join(work, `ipal-kit-${Date.now().toString(36)}-${process.pid}.tgz`)
sh(work, 'mv', [packed, tarball])
const version = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version
const packedBundle = spawnSync('tar', ['-xOzf', tarball, 'package/dist/starter/template.json.gz'], { maxBuffer: 64 * 1024 * 1024 }).stdout
const bundleSha256 = createHash('sha256').update(packedBundle).digest('hex')
const commit = out('git', ['-C', root, 'rev-parse', 'HEAD'])
// 2. MongoDB in its own container, like the Coolify database resource
sh(root, 'docker', ['run', '-d', '--rm', '--name', mongoName, '-p', '127.0.0.1::27017', 'mongo:7'])
mongoStarted = true
const mongoPort = out('docker', ['port', mongoName, '27017']).split(':').pop()
check('MongoDB container', Boolean(mongoPort), `127.0.0.1:${mongoPort}`)
// 3. the developer's command, from the packed tarball
const answersFile = join(work, 'answers.json')
writeFileSync(answersFile, JSON.stringify(answers, null, 2))
const started = Date.now()
const created = sh(work, 'pnpm', ['--config.auto-install-peers=false', '--config.dlx-cache-max-age=0', 'dlx', tarball, 'create', domain, '--answers', answersFile, '--plugin-spec', `file:${tarball}`], {}, { allowFail: true })
check('ipal-kit create (install, skills, tokens, types, import map, typecheck, secret check, first commit)', created === 0, `${((Date.now() - started) / 1000).toFixed(0)} s`)
const site = join(work, 'release-checkexample-web')
// the site was made by THIS tarball: the bundle hash and commit the generator recorded, and the plugin it installed
const made = JSON.parse(readFileSync(join(site, '.ipal', 'starter.json'), 'utf8'))
check('generated by this tarball (bundle sha256, plugin version)', made.source?.bundleSha256 === bundleSha256 && made.ipalKit === version, `${bundleSha256.slice(0, 12)} · ${version}`)
check('bundle built from this commit', (made.source?.commit ?? '').replace(/-dirty$/, '') === commit, made.source?.commit ?? 'none')
const installed = join(site, 'node_modules', '@intecion', 'ipal-kit')
const installedSha = createHash('sha256').update(readFileSync(join(installed, 'dist', 'starter', 'template.json.gz'))).digest('hex')
check('the site installed this tarball', installedSha === bundleSha256 && JSON.parse(readFileSync(join(installed, 'package.json'), 'utf8')).version === version)
check('first commit, nothing left uncommitted', out('git', ['-C', site, 'status', '--porcelain']) === '' && out('git', ['-C', site, 'log', '--oneline']).split('\n').length === 1)
// 4. what Coolify runs: frozen install from the committed lockfile, then build, then start
const env = {
ALLOW_LOCAL_MEDIA: '1', // no R2 in the gate (never set in Coolify)
DATABASE_URI: `mongodb://127.0.0.1:${mongoPort}/release-checkexample_dev`,
IPAL_COOKIE_SCAN_TOKEN: 'release-gate-token-0123456789',
IPAL_COOKIE_SCAN_URL: 'http://127.0.0.1:9',
IPAL_IP_HEADER: 'x-forwarded-for',
NEXT_PUBLIC_SERVER_URL: `http://localhost:${PORT}`,
PAYLOAD_SECRET: readFileSync(join(site, '.env'), 'utf8').match(/^PAYLOAD_SECRET=(.+)$/m)?.[1] ?? '',
}
sh(site, 'pnpm', ['install', '--frozen-lockfile', '--ignore-workspace'], env)
check('Coolify install: pnpm install --frozen-lockfile', true)
sh(site, 'pnpm', ['seed'], { ...env, NODE_ENV: 'development' })
check('first seed of the new local _dev database (before launch)', true)
sh(site, 'pnpm', ['generate:types'], env)
sh(site, 'pnpm', ['build'], env)
check('Coolify build: pnpm generate:types && pnpm build', true)
// 5. the documented targeted seed, in production mode, as in Coolify's Terminal
const prod = { ...env, NODE_ENV: 'production' }
sh(site, 'pnpm', ['seed'], { ...prod, SEED_DRY_RUN: '1', SEED_ONLY: 'pages:kontakt' })
sh(site, 'pnpm', ['seed'], { ...prod, SEED_ONLY: 'pages:kontakt' })
check('targeted seed in production mode: SEED_ONLY="pages:kontakt" [SEED_DRY_RUN=1] pnpm seed', true)
// after launch: a run without SEED_ONLY on production must be refused by the plugin's guard
check('full seed on production (no SEED_ONLY) is refused', fullSeedRefused(site, prod), 'exit 1 with "full seed refused"')
// 6. the production server
log(`$ pnpm start (PORT=${PORT})`)
server = spawn('pnpm', ['start'], { cwd: site, detached: true, env: { ...process.env, ...prod, PORT }, stdio: 'inherit' })
const health = await waitFor(`http://127.0.0.1:${PORT}/api/health`, 90)
check('GET /api/health', health === 200, String(health))
const home = await fetch(`http://127.0.0.1:${PORT}/pl`)
const headers = home.headers
check('GET /pl', home.status === 200, String(home.status))
check('CSP report-only, no X-Powered-By', headers.has('content-security-policy-report-only') && !headers.has('x-powered-by'))
const llms = await (await fetch(`http://127.0.0.1:${PORT}/llms.txt`)).text()
check('llms.txt names the site', llms.includes('Release Check'))
// 7. ipal-doctor, when this ipal-kit ships it
if (existsSync(join(site, 'node_modules', '.bin', 'ipal-doctor'))) {
const doctor = sh(site, 'pnpm', ['exec', 'ipal-doctor', '--strict', '--offline'], env, { allowFail: true })
check('ipal-doctor --strict: zero findings', doctor === 0)
} else {
results.push({ detail: 'not in this ipal-kit yet', name: 'ipal-doctor --strict', ok: null })
log('- ipal-doctor --strict — skipped: not in this ipal-kit yet')
}
// 8. Coolify's build pack itself, when the nixpacks CLI is available
if (out('sh', ['-c', 'command -v nixpacks'])) {
const image = `ipal-starter-gate-site-${process.pid}`
sh(site, 'nixpacks', ['build', '.', '--name', image, '--install-cmd', 'pnpm install --frozen-lockfile', '--build-cmd', 'pnpm generate:types && pnpm build', '--start-cmd', 'pnpm start'], env)
const mongoIp = out('docker', ['inspect', '-f', '{{.NetworkSettings.IPAddress}}', mongoName])
sh(site, 'docker', ['run', '--rm', '-e', `DATABASE_URI=mongodb://${mongoIp}:27017/release-checkexample_dev`, '-e', `PAYLOAD_SECRET=${env.PAYLOAD_SECRET}`, '-e', 'SEED_ONLY=pages:kontakt', '-e', 'SEED_DRY_RUN=1', '-e', 'NODE_ENV=production', image, 'pnpm', 'seed'])
sh(site, 'docker', ['rmi', image], {}, { allowFail: true })
check('targeted seed inside the Nixpacks image', true)
} else {
results.push({ detail: 'nixpacks CLI not on PATH; the same commands ran on the host', name: 'Nixpacks image', ok: null })
log('- Nixpacks image — skipped: nixpacks CLI not on PATH (the same commands ran on the host)')
}
}
function cleanup() {
if (server?.pid) {
try {
process.kill(-server.pid, 'SIGTERM')
} catch {
// already gone
}
}
if (mongoStarted) {spawnSync('docker', ['stop', mongoName], { stdio: 'ignore' })}
if (!keep) {rmSync(work, { force: true, recursive: true })}
}
let failed = false
try {
await main()
} catch (error) {
failed = true
console.error(`[starter:gate] ${error.message}`)
} finally {
cleanup()
}
log(`${failed ? 'FAILED' : 'passed'}: ${results.filter((r) => r.ok).length} checks passed, ${results.filter((r) => r.ok === null).length} skipped`)
process.exit(failed ? 1 : 0)