From 94cf52d60733790c3dd26a4a135adc9f19fc425e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:27:15 +0100 Subject: [PATCH 1/9] test: repo-turbo's publish is handed IMAGE_PREFIX and NPM_CONFIG_USERCONFIG through Turbo (PLX-225) Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/repoTurbo.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index ebaeaf1..d71df0c 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -272,6 +272,14 @@ test('publish is never cached and waits for the build of its own project only, i ); }); +test('publish is handed where the images go and the npmrc of private packages, which Turbo would hide, and hashes nothing', async () => { + // The forge's variables (GITHUB_*), Docker's and BuildKit's (DOCKER_*, BUILDKIT_*) and Next's (NEXT_*) pass by + // Turbo's own list; these two do not. + const { publish } = turboOf(await render()); + assert.deepEqual(publish?.passThroughEnv, ['IMAGE_PREFIX', 'NPM_CONFIG_USERCONFIG']); + assert.equal(publish?.env, undefined); +}); + test('test files are no input of build, and are an input of check and test', async () => { const tasks = turboOf(await render()); assert.deepEqual( From 6292f92abdc66d3337109ca545c0eb5e0458717c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:27:49 +0100 Subject: [PATCH 2/9] repo-turbo: publish passes IMAGE_PREFIX and NPM_CONFIG_USERCONFIG through Turbo's strict environment Turbo 2.11.13 passes GITHUB_*, DOCKER_*, BUILDKIT_*, NEXT_* and HOME to a task by its own list (seen by running a publish script under Turbo, and in the list the binary carries); IMAGE_PREFIX and NPM_CONFIG_USERCONFIG it hides. Co-Authored-By: Claude Opus 5.5 --- templates/repo-turbo/files/turbo.json.jinja | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/templates/repo-turbo/files/turbo.json.jinja b/templates/repo-turbo/files/turbo.json.jinja index 160b2a5..7619796 100644 --- a/templates/repo-turbo/files/turbo.json.jinja +++ b/templates/repo-turbo/files/turbo.json.jinja @@ -46,7 +46,10 @@ // Puts the artifact of an app into a registry: after the build of the same project, and never replayed. "publish": { "dependsOn": ["build"], - "cache": false + "cache": false, + // Where the images go, and the npmrc of private packages for an image built from a pruned context. The forge's, + // Docker's, BuildKit's and Next's variables, the server-actions key among them, pass by Turbo's own list. + "passThroughEnv": ["IMAGE_PREFIX", "NPM_CONFIG_USERCONFIG"] }, {%- endif %} "dev": { From 6bd4fabaaf585e1dee577073c7e01811f3deb070 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:30:06 +0100 Subject: [PATCH 3/9] test: plx-ci image finds or makes an app's image from its build output, against a fake builder and registry (PLX-225) Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/image.test.ts | 258 +++++++++++++++++++++ packages/cli-ci/src/program.test.ts | 2 +- packages/cli-ci/src/testing/fakeDocker.ts | 107 +++++++++ 3 files changed, 366 insertions(+), 1 deletion(-) create mode 100644 packages/cli-ci/src/commands/image.test.ts create mode 100644 packages/cli-ci/src/testing/fakeDocker.ts diff --git a/packages/cli-ci/src/commands/image.test.ts b/packages/cli-ci/src/commands/image.test.ts new file mode 100644 index 0000000..bf60f4c --- /dev/null +++ b/packages/cli-ci/src/commands/image.test.ts @@ -0,0 +1,258 @@ +// plx-ci image as a process, in an app's directory of a checkout, against the +// fake builder and registry of testing/fakeDocker.ts. The machine is told to +// the process through Node's own process.platform and process.arch. +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, test } from 'node:test'; +import { LOCKFILE } from '../testing/checkout.ts'; +import { type Call, fakeDocker } from '../testing/fakeDocker.ts'; + +const BIN = join(import.meta.dirname, '..', 'bin.ts'); +const HASH = '0f2a3f35123dfd73'; +const SOLVER = '9e1d5b7a0c3f2e41'; +const KEY = 'the-apps-key'; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const write = (path: string, content: string) => { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); +}; + +/** + * A committed checkout with two apps: website from app-nextjs, its build output in place with the build ID `id` + * (none where it is undefined), and solver with a Dockerfile of its own, its build ID where Next leaves it. + */ +function checkout(id: string | undefined = HASH): { root: string; sha: string } { + const root = mkdtempSync(join(tmpdir(), 'plx-ci-image-')); + dirs.push(root); + write(join(root, 'package.json'), JSON.stringify({ devDependencies: { turbo: '^2.9.0' } })); + write(join(root, 'pnpm-lock.yaml'), LOCKFILE); + write(join(root, '.dockerignore'), '**/node_modules\n'); + write(join(root, 'apps/website/package.json'), JSON.stringify({ name: '@acme/website' })); + write(join(root, 'apps/website/docker/Dockerfile'), 'FROM scratch\n'); + write(join(root, 'apps/website/.next/standalone/apps/website/server.js'), '\n'); + if (id !== undefined) write(join(root, 'apps/website/.next/standalone/apps/website/.next/BUILD_ID'), id); + write(join(root, 'apps/solver/package.json'), JSON.stringify({ name: '@acme/solver' })); + write(join(root, 'apps/solver/docker/Dockerfile'), 'FROM scratch\n'); + write(join(root, 'apps/solver/.next/BUILD_ID'), SOLVER); + const git = (...args: string[]) => + execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.invalid', ...args], { + cwd: root, + encoding: 'utf8', + }).trim(); + git('init', '-q'); + git('add', '-A'); + git('-c', 'commit.gpgsign=false', 'commit', '-q', '-m', 'one'); + return { root, sha: git('rev-parse', 'HEAD') }; +} + +interface Ran { + status: number | null; + stdout: string; + stderr: string; +} + +/** plx-ci with `args` in `cwd`, the fakes first on the PATH, `env` and nothing else of this process's, on `machine`. */ +function plxCi( + cwd: string, + args: string[], + bin: string, + env: Record = {}, + machine: [string, string] = ['linux', 'x64'], +): Ran { + const [platform, arch] = machine; + const as = `data:text/javascript,Object.defineProperty(process,'platform',{value:'${platform}'});Object.defineProperty(process,'arch',{value:'${arch}'})`; + const ran = spawnSync(process.execPath, ['--import', as, BIN, ...args], { + cwd, + encoding: 'utf8', + env: { PATH: `${bin}:${process.env.PATH}`, HOME: process.env.HOME ?? '', ...env }, + }); + return { status: ran.status, stdout: ran.stdout, stderr: ran.stderr }; +} + +const builds = (calls: Call[]) => calls.filter((c) => c.args[1] === 'build'); +const flagged = (args: string[], flag: string) => args.filter((_, i) => args[i - 1] === flag); + +test('an image the registry holds under build- gets the commit’s tag, and nothing is built', () => { + const { root, sha } = checkout(); + const fake = fakeDocker(root, { holds: [`ghcr.io/acme/website:build-${HASH}`] }); + const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'Acme/web' }); + assert.equal(ran.status, 0, ran.stderr); + assert.equal(ran.stdout, `ghcr.io/acme/website:${sha} (tagged)\n`); + assert.deepEqual( + fake.calls().map((c) => c.args), + [ + ['buildx', 'imagetools', 'inspect', '--format', '{{json .Manifest}}', `ghcr.io/acme/website:build-${HASH}`], + [ + 'buildx', + 'imagetools', + 'create', + '--prefer-index=false', + '--tag', + `ghcr.io/acme/website:${sha}`, + `ghcr.io/acme/website:build-${HASH}`, + ], + ], + ); + // The commit's tag names the very manifest build- does. + assert.equal(fake.held()[`ghcr.io/acme/website:${sha}`], fake.held()[`ghcr.io/acme/website:build-${HASH}`]); +}); + +test('a missing image is built from the build output with the app’s Dockerfile, for linux/amd64, and pushed under both tags', () => { + const { root, sha } = checkout(); + const fake = fakeDocker(root); + const app = join(root, 'apps', 'website'); + // IMAGE_PREFIX names another registry than the forge's; no key is needed, the output holds what the image runs. + const ran = plxCi(app, ['--json', 'image'], fake.bin, { + IMAGE_PREFIX: 'registry.example/Acme/', + GITHUB_REPOSITORY: 'o/r', + }); + assert.equal(ran.status, 0, ran.stderr); + assert.deepEqual(JSON.parse(ran.stdout), { + app: 'website', + image: `registry.example/acme/website:${sha}`, + built: true, + tags: [`build-${HASH}`, sha], + digest: 'sha256:built', + }); + const [build, ...more] = builds(fake.calls()); + assert.equal(more.length, 0); + const args = build?.args ?? []; + assert.deepEqual(args.slice(0, 7), [ + 'buildx', + 'build', + join(app, '.next', 'standalone'), + '--file', + join(app, 'docker', 'Dockerfile'), + '--platform', + 'linux/amd64', + ]); + assert.deepEqual(flagged(args, '--tag'), [ + `registry.example/acme/website:build-${HASH}`, + `registry.example/acme/website:${sha}`, + ]); + assert.deepEqual(flagged(args, '--build-arg'), ['APP=website']); + assert.deepEqual(flagged(args, '--output'), ['type=image,push=true,oci-mediatypes=true']); + assert.ok(args.includes('--provenance=false') && args.includes('--sbom=false'), args.join(' ')); + // No layer cache, no secret and no builder of the BuildKit service: this machine's Docker builds. + assert.doesNotMatch(args.join(' '), /--cache-from|--cache-to|--secret|--builder|BUILD_HASH/); + assert.equal(build?.env.SOURCE_DATE_EPOCH, '0'); + assert.deepEqual(fake.held(), { + [`registry.example/acme/website:build-${HASH}`]: 'sha256:built', + [`registry.example/acme/website:${sha}`]: 'sha256:built', + }); +}); + +test('with BUILDKIT_HOST the image is built by that BuildKit service, through a builder made once', () => { + const { root } = checkout(); + const fake = fakeDocker(root); + const app = join(root, 'apps', 'website'); + const env = { GITHUB_REPOSITORY: 'acme/web', BUILDKIT_HOST: 'tcp://127.0.0.1:4321' }; + assert.equal(plxCi(app, ['image'], fake.bin, env).status, 0); + assert.deepEqual( + fake + .calls() + .filter((c) => ['inspect', 'create'].includes(c.args[1] ?? '')) + .map((c) => c.args), + [ + ['buildx', 'inspect', 'plexus-buildkit'], + ['buildx', 'create', '--name', 'plexus-buildkit', '--driver', 'remote', 'tcp://127.0.0.1:4321'], + ], + ); + assert.deepEqual(flagged(builds(fake.calls())[0]?.args ?? [], '--builder'), ['plexus-buildkit']); + const again = fakeDocker(join(root, 'again'), { builders: ['plexus-buildkit'] }); + assert.equal(plxCi(app, ['image'], again.bin, env).status, 0); + assert.ok(!again.calls().some((c) => c.args[1] === 'create')); +}); + +test('an output without BUILD_ID is refused before the registry is asked', () => { + const { root } = checkout(undefined); + // Next's own BUILD_ID beside the output, which a build cached without it leaves stale, does not count. + write(join(root, 'apps/website/.next/BUILD_ID'), HASH); + const fake = fakeDocker(root); + const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' }); + assert.equal(ran.status, 1); + assert.match(ran.stderr, /\.next\/standalone holds no apps\/website\/\.next\/BUILD_ID/); + assert.deepEqual(fake.calls(), []); +}); + +test('a machine of another platform than Linux x64 is refused before any build, in one line', () => { + const { root } = checkout(); + const fake = fakeDocker(root); + const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' }, [ + 'darwin', + 'arm64', + ]); + assert.equal(ran.status, 1); + assert.equal(ran.stderr.trim().split('\n').length, 1, ran.stderr); + assert.match(ran.stderr, /darwin-arm64.*linux\/amd64/); + assert.deepEqual(builds(fake.calls()), []); + assert.deepEqual(fake.held(), {}); +}); + +test('a refused login is an error, never a missing image', () => { + const { root } = checkout(); + const fake = fakeDocker(root, { refused: true }); + const ran = plxCi(join(root, 'apps', 'website'), ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' }); + assert.equal(ran.status, 1); + assert.match(ran.stderr, /could not look up ghcr\.io\/acme\/website:build-0f2a3f35123dfd73: .*401/s); + assert.deepEqual(builds(fake.calls()), []); +}); + +test('an app with a Dockerfile of its own builds from a pruned context, with its key and the npmrc as secrets', () => { + const { root, sha } = checkout(); + const fake = fakeDocker(root); + const env = { + GITHUB_REPOSITORY: 'acme/web', + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY, + NPM_CONFIG_USERCONFIG: '/run/npmrc', + }; + // On any machine: the Dockerfile builds the app itself, for linux/amd64. + const ran = plxCi(join(root, 'apps', 'solver'), ['image', '--pruned'], fake.bin, env, ['darwin', 'arm64']); + assert.equal(ran.status, 0, ran.stderr); + const calls = fake.calls(); + const [build] = builds(calls); + const args = build?.args ?? []; + const out = dirname(args[2] ?? ''); + assert.equal(args[2], join(out, 'full')); + assert.deepEqual(args.slice(3, 5), ['--file', join(out, 'full', 'apps', 'solver', 'docker', 'Dockerfile')]); + assert.deepEqual(flagged(args, '--build-arg'), ['APP=solver', `BUILD_HASH=${SOLVER}`]); + assert.deepEqual(flagged(args, '--secret'), [ + 'id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY', + 'id=npmrc,src=/run/npmrc', + ]); + assert.deepEqual(flagged(args, '--tag'), [`ghcr.io/acme/solver:build-${SOLVER}`, `ghcr.io/acme/solver:${sha}`]); + // The key reaches the build from the environment, never on its command line. + assert.equal(build?.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, KEY); + assert.ok(!args.some((a) => a.includes(KEY))); + // The context was completed to the repo root's layout, and is removed after. + assert.ok(!existsSync(out), `${out} is left behind`); +}); + +test('a build from a pruned context refuses without the key; a tag needs none', () => { + const { root } = checkout(); + const fake = fakeDocker(root); + const solver = join(root, 'apps', 'solver'); + const ran = plxCi(solver, ['image', '--pruned'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' }); + assert.equal(ran.status, 2); + assert.match(ran.stderr, /NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty/); + assert.deepEqual(builds(fake.calls()), []); + const there = fakeDocker(join(root, 'there'), { holds: [`ghcr.io/acme/solver:build-${SOLVER}`] }); + assert.equal(plxCi(solver, ['image', '--pruned'], there.bin, { GITHUB_REPOSITORY: 'acme/web' }).status, 0); +}); + +test('it runs in an app’s directory, apps/ of a checkout, and nowhere else', () => { + const { root } = checkout(); + const fake = fakeDocker(root); + const ran = plxCi(root, ['image'], fake.bin, { GITHUB_REPOSITORY: 'acme/web' }); + assert.equal(ran.status, 2); + assert.match(ran.stderr, /apps\//); + assert.deepEqual(fake.calls(), []); +}); diff --git a/packages/cli-ci/src/program.test.ts b/packages/cli-ci/src/program.test.ts index 272e187..2d4e4f1 100644 --- a/packages/cli-ci/src/program.test.ts +++ b/packages/cli-ci/src/program.test.ts @@ -35,7 +35,7 @@ test('help lists the global options', () => { test('the universal commands take --strategy, and hybrid holds the instances’ three', () => { const program = buildProgram(); const names = program.commands.map((c) => c.name()); - assert.deepEqual(names, ['plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); + assert.deepEqual(names, ['plan', 'publish', 'image', 'display-versions', 'tag-display-version', 'hybrid']); for (const name of ['plan']) { const command = program.commands.find((c) => c.name() === name); assert.ok( diff --git a/packages/cli-ci/src/testing/fakeDocker.ts b/packages/cli-ci/src/testing/fakeDocker.ts new file mode 100644 index 0000000..80d55e7 --- /dev/null +++ b/packages/cli-ci/src/testing/fakeDocker.ts @@ -0,0 +1,107 @@ +// A fake builder and a fake forge's registry, for the tests that run plx-ci as +// a process: a `docker` on the PATH that answers the buildx commands plx-ci +// gives, keeps what the registry holds in a file of its directory, and records +// every call with the environment a build is given; and an `npx` whose Turbo +// prunes into the directory it is told, as `turbo prune --docker` lays it out. +// Not shipped (excluded in tsconfig). +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +/** One call of the fake docker: its arguments, and the variables a build reads, where they were set. */ +export interface Call { + args: string[]; + env: Record; +} + +export interface FakeDocker { + /** The directory to put first on the PATH. */ + bin: string; + calls(): Call[]; + /** What the registry holds, reference → digest. */ + held(): Record; +} + +/** The variables of a build the tests look at. */ +const SEEN = ['SOURCE_DATE_EPOCH', 'NEXT_SERVER_ACTIONS_ENCRYPTION_KEY']; + +const DOCKER = `#!/usr/bin/env node +const fs = require('node:fs'); +const path = require('node:path'); +const dir = path.dirname(fs.realpathSync(process.argv[1])); +const state = path.join(dir, 'state.json'); +const s = JSON.parse(fs.readFileSync(state, 'utf8')); +const args = process.argv.slice(2); +const env = Object.fromEntries(${JSON.stringify(SEEN)}.filter((n) => n in process.env).map((n) => [n, process.env[n]])); +fs.appendFileSync(path.join(dir, 'calls.jsonl'), JSON.stringify({ args, env }) + '\\n'); +const save = () => fs.writeFileSync(state, JSON.stringify(s)); +const fail = (line) => { process.stderr.write(line + '\\n'); process.exit(1); }; +const value = (flag) => args[args.indexOf(flag) + 1]; +const [group, verb, sub] = args; +if (group !== 'buildx') fail('fake docker: no ' + args.join(' ')); +if (verb === 'imagetools' && sub === 'inspect') { + const ref = args.at(-1); + if (s.refused) fail('ERROR: failed to authorize: unexpected status from GET request: 401 Unauthorized'); + if (!(ref in s.held)) fail('ERROR: ' + ref + ': not found'); + process.stdout.write(JSON.stringify({ mediaType: 'application/vnd.oci.image.manifest.v1+json', digest: s.held[ref], size: 476 }, null, 2) + '\\n'); +} else if (verb === 'imagetools' && sub === 'create') { + const from = args.at(-1); + if (!(from in s.held)) fail('ERROR: ' + from + ': not found'); + s.held[value('--tag')] = s.held[from]; + save(); +} else if (verb === 'inspect') { + if (!s.builders.includes(args[2])) fail('ERROR: no builder ' + JSON.stringify(args[2]) + ' found'); +} else if (verb === 'create') { + s.builders.push(value('--name')); + save(); +} else if (verb === 'build') { + if (!fs.existsSync(args[2])) fail('ERROR: no context ' + args[2]); + args.forEach((a, i) => { if (args[i - 1] === '--tag') s.held[a] = 'sha256:built'; }); + fs.writeFileSync(value('--metadata-file'), JSON.stringify({ 'containerimage.digest': 'sha256:built' })); + save(); +} else fail('fake docker: no ' + args.join(' ')); +`; + +// npx --yes turbo@ prune --docker --out-dir : the lockfile beside full/ and json/. +const NPX = `#!/usr/bin/env node +const fs = require('node:fs'); +const path = require('node:path'); +const args = process.argv.slice(2); +if (!args.includes('prune')) { process.stderr.write('fake npx: no ' + args.join(' ') + '\\n'); process.exit(1); } +const out = args[args.indexOf('--out-dir') + 1]; +for (const sub of ['full', 'json']) fs.mkdirSync(path.join(out, sub), { recursive: true }); +fs.writeFileSync(path.join(out, 'pnpm-lock.yaml'), 'lockfileVersion: 9.0\\n'); +`; + +/** The fakes in `dir`, with a registry that holds `holds` (each under its own digest) and the builders `builders`. */ +export function fakeDocker( + dir: string, + options: { holds?: string[]; builders?: string[]; refused?: boolean } = {}, +): FakeDocker { + const bin = join(dir, 'bin'); + mkdirSync(bin, { recursive: true }); + const held = Object.fromEntries((options.holds ?? []).map((ref, i) => [ref, `sha256:held${i}`])); + writeFileSync( + join(bin, 'state.json'), + JSON.stringify({ held, builders: options.builders ?? [], refused: options.refused ?? false }), + ); + for (const [name, script] of [ + ['docker', DOCKER], + ['npx', NPX], + ] as const) { + writeFileSync(join(bin, name), script); + chmodSync(join(bin, name), 0o755); + } + const callsFile = join(bin, 'calls.jsonl'); + return { + bin, + calls: () => + existsSync(callsFile) + ? readFileSync(callsFile, 'utf8') + .trim() + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line) as Call) + : [], + held: () => JSON.parse(readFileSync(join(bin, 'state.json'), 'utf8')).held, + }; +} From 0c2b909c139e29f9586a95e74af13eb857a79398 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:31:59 +0100 Subject: [PATCH 4/9] test: an output without BUILD_ID is made with null, which a default parameter does not replace The test passed undefined to a parameter whose default is the hash, so its checkout held a BUILD_ID after all. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/image.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cli-ci/src/commands/image.test.ts b/packages/cli-ci/src/commands/image.test.ts index bf60f4c..347cb56 100644 --- a/packages/cli-ci/src/commands/image.test.ts +++ b/packages/cli-ci/src/commands/image.test.ts @@ -27,9 +27,9 @@ const write = (path: string, content: string) => { /** * A committed checkout with two apps: website from app-nextjs, its build output in place with the build ID `id` - * (none where it is undefined), and solver with a Dockerfile of its own, its build ID where Next leaves it. + * (none where it is null), and solver with a Dockerfile of its own, its build ID where Next leaves it. */ -function checkout(id: string | undefined = HASH): { root: string; sha: string } { +function checkout(id: string | null = HASH): { root: string; sha: string } { const root = mkdtempSync(join(tmpdir(), 'plx-ci-image-')); dirs.push(root); write(join(root, 'package.json'), JSON.stringify({ devDependencies: { turbo: '^2.9.0' } })); @@ -38,7 +38,7 @@ function checkout(id: string | undefined = HASH): { root: string; sha: string } write(join(root, 'apps/website/package.json'), JSON.stringify({ name: '@acme/website' })); write(join(root, 'apps/website/docker/Dockerfile'), 'FROM scratch\n'); write(join(root, 'apps/website/.next/standalone/apps/website/server.js'), '\n'); - if (id !== undefined) write(join(root, 'apps/website/.next/standalone/apps/website/.next/BUILD_ID'), id); + if (id !== null) write(join(root, 'apps/website/.next/standalone/apps/website/.next/BUILD_ID'), id); write(join(root, 'apps/solver/package.json'), JSON.stringify({ name: '@acme/solver' })); write(join(root, 'apps/solver/docker/Dockerfile'), 'FROM scratch\n'); write(join(root, 'apps/solver/.next/BUILD_ID'), SOLVER); @@ -173,7 +173,7 @@ test('with BUILDKIT_HOST the image is built by that BuildKit service, through a }); test('an output without BUILD_ID is refused before the registry is asked', () => { - const { root } = checkout(undefined); + const { root } = checkout(null); // Next's own BUILD_ID beside the output, which a build cached without it leaves stale, does not count. write(join(root, 'apps/website/.next/BUILD_ID'), HASH); const fake = fakeDocker(root); From ef10d263f0210d13250823baff217bde006b6d20 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:32:14 +0100 Subject: [PATCH 5/9] plx-ci image: an app's image found or made from the build output on disk, for the checkout's commit The helper an app's publish script runs, in apps/ after its build: the build ID the output holds names build-; where the registry holds it, the commit's tag is added with buildx imagetools, else the image is built from the output (or, with --pruned, from a pruned context with the app's own Dockerfile) and pushed under both. A machine other than Linux x64 is refused before it builds from an output. build.ts builds from the directory it is handed; the restore of the old publish moves into core/publish.ts, which goes with that command, and packageName, turboOf and ImageContext move from plan.ts to build.ts, which keeps using them. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/image.ts | 46 +++++++ packages/cli-ci/src/commands/index.ts | 8 +- packages/cli-ci/src/commands/publish.ts | 2 +- packages/cli-ci/src/core/build.ts | 167 +++++++++++------------- packages/cli-ci/src/core/image.ts | 119 +++++++++++++++++ packages/cli-ci/src/core/plan.ts | 30 +---- packages/cli-ci/src/core/publish.ts | 69 ++++++++-- packages/cli-ci/src/core/registry.ts | 50 +++++-- 8 files changed, 342 insertions(+), 149 deletions(-) create mode 100644 packages/cli-ci/src/commands/image.ts create mode 100644 packages/cli-ci/src/core/image.ts diff --git a/packages/cli-ci/src/commands/image.ts b/packages/cli-ci/src/commands/image.ts new file mode 100644 index 0000000..646e72a --- /dev/null +++ b/packages/cli-ci/src/commands/image.ts @@ -0,0 +1,46 @@ +// plx-ci image [--pruned]: the image of the app in the current directory, +// apps/ of a checkout, for the checkout's commit, in the forge's +// registry: tagged where build- is there already, else built and pushed +// under both (core/image.ts says how). What an app's `publish` script runs, +// after its build: `plx-ci image` for an app from app-nextjs, whose image +// copies the build output; `plx-ci image --pruned` for an app whose own +// Dockerfile builds it from a pruned context. Needs git, and Docker's client +// with buildx logged in to the registry (DOCKER_CONFIG, else ~/.docker). From +// the environment: IMAGE_PREFIX, where the images live (default +// ghcr.io/); BUILDKIT_HOST, the BuildKit service +// to build through, which a slot of a runner host is handed, else this +// machine's Docker builds; and, for --pruned alone, +// NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, the repo's server-actions key, and +// NPM_CONFIG_USERCONFIG, a user-level npmrc with the token of the tenant's +// private package registry, both handed to the Dockerfile as BuildKit +// secrets. Prints the image under the commit's tag. +// +// "publish": "plx-ci image" + +import { imagePrefix } from '@plexus-ms/lib'; +import type { Command } from 'commander'; +import { image } from '../core/image.ts'; +import { contextOf } from '../program.ts'; + +export function register(program: Command): void { + program + .command('image') + .description( + 'the image of the app in this directory for the commit: tag build- where the registry holds it, else build it from the build output and push both tags', + ) + .option('--pruned', 'build with the app’s own Dockerfile, from a context turbo prune makes') + .action(async (opts: { pruned?: boolean }, command: Command) => { + const ctx = contextOf(command); + const env = process.env; + const result = await image(ctx, { + dir: process.cwd(), + context: opts.pruned ? 'pruned' : 'output', + prefix: imagePrefix(env), + machine: `${process.platform}-${process.arch}`, + encryptionKey: env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY || undefined, + npmrc: env.NPM_CONFIG_USERCONFIG || undefined, + buildkit: env.BUILDKIT_HOST || undefined, + }); + ctx.result(result, (r) => `${r.image}${r.built ? ` (built, ${r.digest ?? 'no digest'})` : ' (tagged)'}`); + }); +} diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index b79524b..b58dd9b 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -1,13 +1,15 @@ // Every command of plx-ci, in the order `plx-ci --help` lists them. Same rule // as plx: a command module maps argv onto core/ and nothing more, and the // logic, the planning and the tests live in core/. The universal commands -// come first, in the order a run uses them, and read the strategy; `hybrid` -// holds what only that strategy needs. The display versions, opt-in per +// come first, in the order a run uses them, and read the strategy; `image`, +// which an app's own publish script runs, reads none and follows publish; +// `hybrid` holds what only that strategy needs. The display versions, opt-in per // repo, read no strategy and sit where a release uses them, after publish. import type { Command } from 'commander'; import { register as displayVersions } from './displayVersions.ts'; import { register as hybrid } from './hybrid.ts'; +import { register as image } from './image.ts'; import { register as plan } from './plan.ts'; import { register as publish } from './publish.ts'; -export const commands: ((program: Command) => void)[] = [plan, publish, displayVersions, hybrid]; +export const commands: ((program: Command) => void)[] = [plan, publish, image, displayVersions, hybrid]; diff --git a/packages/cli-ci/src/commands/publish.ts b/packages/cli-ci/src/commands/publish.ts index 2fa0c39..104ffc3 100644 --- a/packages/cli-ci/src/commands/publish.ts +++ b/packages/cli-ci/src/commands/publish.ts @@ -20,7 +20,7 @@ import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; import type { Command } from 'commander'; import { Option } from 'commander'; -import type { ImageContext } from '../core/plan.ts'; +import type { ImageContext } from '../core/build.ts'; import { publish } from '../core/publish.ts'; import { contextOf } from '../program.ts'; import { imagePrefix } from './shared.ts'; diff --git a/packages/cli-ci/src/core/build.ts b/packages/cli-ci/src/core/build.ts index 85f993f..b32da59 100644 --- a/packages/cli-ci/src/core/build.ts +++ b/packages/cli-ci/src/core/build.ts @@ -1,20 +1,12 @@ -// Build one app's image and push it (§ 4 PLX-Delivery), for publish, which -// builds only an image the forge's registry lacks. An app's image is made in -// one of two ways, by what its Dockerfile is, the context the plan gives it -// (plan.ts's imageContextOf): +// Build one app's image and push it (§ 4 PLX-Delivery), for an image the +// forge's registry lacks. An app's image is made in one of two ways, by what +// its Dockerfile is: // // output an app from app-nextjs: its Dockerfile only copies the one // directory its build leaves (apps//.next/standalone), and -// that directory is the build context. It is restored by the -// repo's own verb, `mise run build `, which a job runs -// against the trusted cache, where the app's e2e job left it; the -// directory is removed first, so that the image holds the restore -// and nothing a server or an earlier build wrote there. A miss -// builds the app, with the app's key, as the e2e job did. The -// output must hold apps//.next/BUILD_ID, the build's hash -// (generateBuildId in the template's next.config.ts), equal to -// the hash the image is tagged with: an output of another hash, or -// none where the Dockerfile's WORKDIR looks, is refused. +// that directory, as the caller hands it over, is the build +// context; the Dockerfile is apps//docker/Dockerfile of the +// checkout. Nothing is built or restored here. // pruned an app with a Dockerfile of its own builds itself in it, from // `turbo prune --docker` (the Turbo the lockfile // has) into a temporary directory: `json/` with the package @@ -27,58 +19,83 @@ // where the job has one, the npmrc of the tenant's private // packages. `json/` goes unused. The directory is removed after. // -// Either way the image is built for linux/amd64 and pushed under build- -// and the commit, with no layer cache, SOURCE_DATE_EPOCH fixing the times -// BuildKit sets, and no provenance or SBOM, so that the manifest is the image -// and nothing else. No rewrite-timestamp: the runner's Docker of the forge -// refuses it beside the unpack of its image store, and an image is built once -// per hash, so no two builds of it are compared. BuildKit's log is the -// job's, at every verbosity. Where the build runs is told apart at this step -// by BUILDKIT_HOST alone, which knows no strategy: a slot of a runner host, -// under on-prem and hybrid, is handed the address of the host's BuildKit -// service there (actions_runners, from the port the service listens on), and -// the build goes through a buildx builder of the remote driver to it, -// plexus-buildkit, made where the machine has none of the name yet; without -// it, as on the forge's runners under github, the runner's own Docker builds -// (the default builder). The push uses the login of the job's -// ~/.docker/config.json, which BuildKit is handed through the build's session. +// Either way the image is built for linux/amd64 and pushed under the two +// references the caller names, build- and the commit, with no layer +// cache, SOURCE_DATE_EPOCH fixing the times BuildKit sets, and no provenance +// or SBOM, so that the manifest is the image and nothing else: one OCI image +// manifest for linux/amd64, its config and its layers. No rewrite-timestamp: +// the runner's Docker of the forge refuses it beside the unpack of its image +// store, and an image is built once per hash, so no two builds of it are +// compared. BuildKit's log is the job's, at every verbosity. Where the build +// runs is told apart by BUILDKIT_HOST alone, which knows no strategy: a slot +// of a runner host is handed the address of the host's BuildKit service there +// (actions_runners, from the port the service listens on), and the build goes +// through a buildx builder of the remote driver to it, plexus-buildkit, made +// where the machine has none of the name yet; without it, as on the forge's +// runners, the machine's own Docker builds (the default builder). The push +// uses the login of Docker's config (DOCKER_CONFIG, else ~/.docker), which +// BuildKit is handed through the build's session. import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { Context, Step } from '@plexus-ms/lib'; import { run, UsageError } from '@plexus-ms/lib'; -import { type ImageContext, packageName, turboOf } from './plan.ts'; +import { parseAllDocuments } from 'yaml'; /** The buildx builder of the remote driver that reaches it. */ export const BUILDER = 'plexus-buildkit'; +/** What an app's image is made from: the directory its build leaves, or a pruned context its own Dockerfile builds in. */ +export type ImageContext = 'output' | 'pruned'; + export interface BuildOptions { app: string; - /** Turbo's hash of the app's build task; the image's tag build- and its build ID. */ + /** The checkout's root. */ + root: string; + /** Turbo's hash of the app's build task; a Dockerfile of the app's own is given it as BUILD_HASH. */ hash: string; - /** The commit, the image's second tag. */ - sha: string; - /** The image, `/`, without a tag. */ - image: string; + /** The references the image is pushed under: build- and the commit's. */ + refs: string[]; /** What the image is made from. */ context: ImageContext; - /** The checkout. */ - dir: string; - /** The app's server-actions key: for a build of the output that misses the cache, or a secret of a Dockerfile of its own. */ - encryptionKey: string; + /** The build output, the build context of `output`. */ + output: string; + /** The app's server-actions key: a secret of a Dockerfile of its own. */ + encryptionKey?: string; /** A user-level npmrc with the token of the tenant's private package registry, a secret of a Dockerfile of its own. */ npmrc?: string; - /** The BuildKit service to build through, `tcp://
:` (BUILDKIT_HOST); without it the runner's Docker. */ + /** The BuildKit service to build through, `tcp://
:` (BUILDKIT_HOST); without it the machine's Docker. */ buildkit?: string; } export interface Built { - tags: string[]; digest?: string; } -/** The output directory of an app from app-nextjs: the build context of its image. */ -export const outputOf = (dir: string, app: string): string => join(dir, 'apps', app, '.next', 'standalone'); +/** The name of an app's package, `apps//package.json`: what Turbo calls it. */ +export async function packageName(ctx: Context, dir: string, app: string): Promise { + const pkg = JSON.parse(await ctx.readFile(`${dir}/apps/${app}/package.json`)) as { name?: string }; + if (!pkg.name) throw new UsageError(`apps/${app}/package.json has no name`); + return pkg.name; +} + +/** + * Turbo at the version the repo's lockfile has for its root, `turbo@`, + * which npx runs without an install. pnpm 11 and later write the package + * manager's own document before the workspace's; the workspace's is the one + * whose root lists turbo. + */ +export async function turboOf(ctx: Context, dir: string): Promise { + const text = await ctx.readFile(`${dir}/pnpm-lock.yaml`); + for (const doc of parseAllDocuments(text)) { + const lock = (Array.isArray(doc) ? undefined : doc.toJS()) as { + importers?: Record }>; + } | null; + const version = lock?.importers?.['.']?.devDependencies?.turbo?.version; + if (version) return `turbo@${version}`; + } + throw new UsageError('pnpm-lock.yaml locks no turbo for the workspace root, which the repo’s verbs run'); +} /** The `docker buildx build` arguments for a context and a Dockerfile, so that the tests pin them. */ export function buildArgs( @@ -88,7 +105,6 @@ export function buildArgs( metadataFile: string, builder?: string, ): string[] { - const { app, image } = options; const own = options.context === 'pruned' ? [ @@ -109,12 +125,9 @@ export function buildArgs( 'linux/amd64', ...(builder ? ['--builder', builder] : []), '--build-arg', - `APP=${app}`, + `APP=${options.app}`, ...own, - '--tag', - `${image}:build-${options.hash}`, - '--tag', - `${image}:${options.sha}`, + ...options.refs.flatMap((ref) => ['--tag', ref]), '--output', 'type=image,push=true,oci-mediatypes=true', '--provenance=false', @@ -131,7 +144,7 @@ export function buildStep(args: string[], env: NodeJS.ProcessEnv): Step { return run('docker', args, { env, interactive: true }); } -/** The builder: the remote one of the BuildKit service where one is given, made where missing; none, the runner's Docker, otherwise. */ +/** The builder: the remote one of the BuildKit service where one is given, made where missing; none, the machine's Docker, otherwise. */ async function builderFor(ctx: Context, options: BuildOptions): Promise { if (!options.buildkit) return undefined; if (!ctx.dryRun) { @@ -144,38 +157,9 @@ async function builderFor(ctx: Context, options: BuildOptions): Promise { - const { app, dir, hash } = options; - const output = outputOf(dir, app); - await ctx.apply([ - run('rm', ['-rf', output]), - run('mise', ['run', 'build', app], { - cwd: dir, - env: { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey }, - }), - ]); - if (!ctx.dryRun) { - const where = `apps/${app}/.next/standalone`; - let id: string; - try { - id = (await ctx.readFile(join(output, 'apps', app, '.next', 'BUILD_ID'))).trim(); - } catch { - throw new Error( - `${where} holds no apps/${app}/.next/BUILD_ID: the build left no app at the place the Dockerfile starts it`, - ); - } - if (id !== hash) - throw new Error( - `${where} holds the build ${id}, not ${hash}: the plan and the build saw different inputs (another Turbo, or another PLX_PLATFORM)`, - ); - } - return output; -} - /** A pruned context of the app, in a new temporary directory; its build context is `/full`. */ async function prunedContext(ctx: Context, options: BuildOptions, out: string): Promise { - const { dir } = options; + const { root } = options; const context = join(out, 'full'); // turbo writes the lockfile beside `full`, and leaves out the root // .dockerignore and an empty packages/ when the app uses none; the @@ -185,32 +169,32 @@ async function prunedContext(ctx: Context, options: BuildOptions, out: string): 'npx', [ '--yes', - await turboOf(ctx, dir), + await turboOf(ctx, root), 'prune', - await packageName(ctx, dir, options.app), + await packageName(ctx, root, options.app), '--docker', '--out-dir', out, ], - { cwd: dir }, + { cwd: root }, ), run('cp', [join(out, 'pnpm-lock.yaml'), join(context, 'pnpm-lock.yaml')]), - run('cp', [join(dir, '.dockerignore'), join(context, '.dockerignore')]), + run('cp', [join(root, '.dockerignore'), join(context, '.dockerignore')]), run('mkdir', ['-p', join(context, 'packages')]), ]); return context; } -/** Build the app's image from its context and push it under build- and the commit. */ +/** Build the app's image from its context and push it under its references. */ export async function build(ctx: Context, options: BuildOptions): Promise { - if (!options.encryptionKey) throw new UsageError('NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty'); + const pruned = options.context === 'pruned'; + if (pruned && !options.encryptionKey) throw new UsageError('NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty'); const { app } = options; const builder = await builderFor(ctx, options); const out = join(tmpdir(), `plx-ci-build-${randomBytes(4).toString('hex')}`); - const pruned = options.context === 'pruned'; - const context = pruned ? await prunedContext(ctx, options, out) : await restoreOutput(ctx, options); + const context = pruned ? await prunedContext(ctx, options, out) : options.output; if (!pruned) await ctx.apply([run('mkdir', ['-p', out])]); - const dockerfile = join(pruned ? context : options.dir, 'apps', app, 'docker', 'Dockerfile'); + const dockerfile = join(pruned ? context : options.root, 'apps', app, 'docker', 'Dockerfile'); const metadataFile = join(out, 'metadata.json'); const env = { SOURCE_DATE_EPOCH: '0', @@ -219,12 +203,11 @@ export async function build(ctx: Context, options: BuildOptions): Promise const t = Date.now(); await ctx.apply([buildStep(buildArgs(options, context, dockerfile, metadataFile, builder), env)]); ctx.say(`build: ${app} ${Math.round((Date.now() - t) / 1000)}s`); - const tags = [`build-${options.hash}`, options.sha]; - const result: Built = { tags }; + const result: Built = {}; if (!ctx.dryRun) { const meta = JSON.parse(await ctx.readFile(metadataFile)) as { 'containerimage.digest'?: string }; result.digest = meta['containerimage.digest']; - ctx.say(`build: ${options.image} ${tags.join(' ')} -> ${result.digest ?? ''}`); + ctx.say(`build: ${options.refs.join(' ')} -> ${result.digest ?? ''}`); } await ctx.apply([run('rm', ['-rf', out])]); return result; diff --git a/packages/cli-ci/src/core/image.ts b/packages/cli-ci/src/core/image.ts new file mode 100644 index 0000000..239952e --- /dev/null +++ b/packages/cli-ci/src/core/image.ts @@ -0,0 +1,119 @@ +// The image of one app, found or made for the commit (§ 4 PLX-Delivery): what +// an app's `publish` script runs, in the app's directory, apps/ of a +// checkout, after its `build`, in the same job and on the same machine as the +// `e2e` that ran against the same output. The steps: +// +// 1. the hash: the build ID the output holds, which is Turbo's hash of the +// app's build task (generateBuildId in app-nextjs's next.config.ts); an +// output without one is refused. No Turbo dry run, no cache restore. +// 2. the names: `/:build-` and `/:` +// (imageRef of @plexus-ms/lib, PLX-App), the commit the checkout's HEAD. +// 3. the registry: where it holds build-, that manifest gets the +// commit's tag, as it is (`docker buildx imagetools create +// --prefer-index=false`, which copies the manifest and wraps it in no +// index), and nothing is built. +// 4. the build, where it does not: build.ts, pushing both tags. +// +// Two modes, by what the app's Dockerfile is; the app's `publish` script +// names its mode by how it calls the helper: +// +// output (default) an app from app-nextjs, whose Dockerfile copies the +// directory its build left, .next/standalone; the build ID is read +// where the Dockerfile starts the app, at +// .next/standalone/apps//.next/BUILD_ID. That output runs +// only on the platform it was built on, so a machine other than +// Linux x64 is refused before it builds. +// pruned (--pruned) an app whose Dockerfile builds the app itself, from a +// context `turbo prune` makes; the build ID is Next's, +// .next/BUILD_ID, and the build may run on any machine. +// +// The image's manifest holds one image for linux/amd64, its config and its +// layers, and nothing else: no provenance, no SBOM (build.ts). The registry is +// the one place that says whether an image exists; nothing else is recorded, +// and that the image was tested follows from the order of the job's steps. +import { basename, dirname, join } from 'node:path'; +import type { Context } from '@plexus-ms/lib'; +import { imageRef, run, UsageError } from '@plexus-ms/lib'; +import { build, type ImageContext } from './build.ts'; +import { imageDigest } from './registry.ts'; + +/** The one platform whose build output the image may copy, as Node names it. */ +const LINUX_X64 = 'linux-x64'; + +export interface ImageOptions { + /** The app's directory, apps/ of a checkout. */ + dir: string; + context: ImageContext; + /** Where the images live, `/`. */ + prefix: string; + /** The machine, `-` as Node names them. */ + machine: string; + /** The app's server-actions key, a secret of a Dockerfile of its own. */ + encryptionKey?: string; + /** A user-level npmrc with the token of the tenant's private package registry, a secret of a Dockerfile of its own. */ + npmrc?: string; + /** The BuildKit service to build through, `tcp://
:`; without it the machine's Docker. */ + buildkit?: string; +} + +export interface Image { + app: string; + /** The image under the commit's tag. */ + image: string; + /** Whether the image was built here, or found under build-. */ + built: boolean; + tags: string[]; + digest?: string; +} + +/** The build ID the output holds, which names the image's build-. */ +async function hashOf(ctx: Context, dir: string, app: string, context: ImageContext): Promise { + const path = context === 'output' ? `.next/standalone/apps/${app}/.next/BUILD_ID` : '.next/BUILD_ID'; + let id = ''; + try { + id = (await ctx.readFile(join(dir, path))).trim(); + } catch {} + if (!id) + throw new Error( + context === 'output' + ? `.next/standalone holds no apps/${app}/.next/BUILD_ID: no build output where the Dockerfile starts the app; run the build first` + : `no .next/BUILD_ID: the app's build left no build ID to name the image by; run the build first`, + ); + return id; +} + +export async function image(ctx: Context, options: ImageOptions): Promise { + const { dir, context, prefix } = options; + const app = basename(dir); + if (basename(dirname(dir)) !== 'apps') + throw new UsageError(`${dir} is no app's directory: run plx-ci image in apps/ of a checkout`); + const hash = await hashOf(ctx, dir, app, context); + const commit = (await ctx.read('git', ['rev-parse', 'HEAD'], { cwd: dir })).trim(); + const target = imageRef(prefix, app, `build-${hash}`); + const ref = imageRef(prefix, app, commit); + const tags = [`build-${hash}`, commit]; + if ((await imageDigest(ctx, target)) !== undefined) { + ctx.say(`image: ${target} is there already, tagging it ${commit}`); + await ctx.apply([run('docker', ['buildx', 'imagetools', 'create', '--prefer-index=false', '--tag', ref, target])]); + return { app, image: ref, built: false, tags }; + } + if (context === 'output' && options.machine !== LINUX_X64) + throw new Error( + `this machine is ${options.machine}, and the build output runs only where it was built; the image is for linux/amd64, so publish it from a build on Linux x64`, + ); + ctx.say( + `image: ${target} is missing, building it from ${context === 'output' ? 'the build output' : 'a pruned context'}`, + ); + const built = await build(ctx, { + app, + root: dirname(dirname(dir)), + hash, + refs: [target, ref], + context, + output: join(dir, '.next', 'standalone'), + encryptionKey: options.encryptionKey, + npmrc: options.npmrc, + buildkit: options.buildkit, + }); + return { app, image: ref, built: true, tags, ...(built.digest ? { digest: built.digest } : {}) }; +} diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index c236003..0588dd2 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -58,7 +58,7 @@ // one no build ever has. import type { Context, EnvironmentTargets } from '@plexus-ms/lib'; import { ExecError, MARKER_FILE, parseMarkerConfig, run as step, UsageError, write } from '@plexus-ms/lib'; -import { parseAllDocuments } from 'yaml'; +import { type ImageContext, packageName, turboOf } from './build.ts'; import { craneDigest, imageName } from './registry.ts'; import { runnerOf, type Strategy } from './strategy.ts'; @@ -142,31 +142,6 @@ export async function appsOf(ctx: Context, dir: string): Promise { .sort(); } -/** The name of an app's package, `apps//package.json`: what Turbo calls it. */ -export async function packageName(ctx: Context, dir: string, app: string): Promise { - const pkg = JSON.parse(await ctx.readFile(`${dir}/apps/${app}/package.json`)) as { name?: string }; - if (!pkg.name) throw new UsageError(`apps/${app}/package.json has no name`); - return pkg.name; -} - -/** - * Turbo at the version the repo's lockfile has for its root, `turbo@`, - * which npx runs without an install. pnpm 11 and later write the package - * manager's own document before the workspace's; the workspace's is the one - * whose root lists turbo. - */ -export async function turboOf(ctx: Context, dir: string): Promise { - const text = await ctx.readFile(`${dir}/pnpm-lock.yaml`); - for (const doc of parseAllDocuments(text)) { - const lock = (Array.isArray(doc) ? undefined : doc.toJS()) as { - importers?: Record }>; - } | null; - const version = lock?.importers?.['.']?.devDependencies?.turbo?.version; - if (version) return `turbo@${version}`; - } - throw new UsageError('pnpm-lock.yaml locks no turbo for the workspace root, which the repo’s verbs run'); -} - /** A hash with nothing known of the cache. */ const forgotten = ({ cached: _, hits: __, ...hash }: Hash): Hash => hash; @@ -244,9 +219,6 @@ export async function readHashes( } } -/** What publish makes an app's image from: the directory its build leaves, or a pruned context its own Dockerfile builds in. */ -export type ImageContext = 'output' | 'pruned'; - /** An app's image context: `output` where its marker lists the template app-nextjs, whose Dockerfile only copies the build output; `pruned` otherwise. */ export async function imageContextOf(ctx: Context, dir: string, app: string): Promise { const path = `apps/${app}/${MARKER_FILE}`; diff --git a/packages/cli-ci/src/core/publish.ts b/packages/cli-ci/src/core/publish.ts index aa4396f..f2ea7fc 100644 --- a/packages/cli-ci/src/core/publish.ts +++ b/packages/cli-ci/src/core/publish.ts @@ -1,16 +1,25 @@ // Publish one app's image under its commit in the forge's registry, the one -// production pulls from (§ 4 PLX-Delivery). Where the registry holds -// `build-` already, the image built for the same content by an earlier -// run, a promotion's among them, gets the commit's tag and nothing is built -// (crane, logged in to the registry by the job). Where it lacks it, the image -// is built and pushed under both tags (build.ts says how). The registry is -// the one place that says whether an image exists; publish records nothing -// else, and that the image was tested is the order of the jobs: a run's -// publish of an app follows that run's test and e2e jobs. +// production pulls from (§ 4 PLX-Delivery), in a job of its own after the +// run's e2e jobs. Where the registry holds `build-` already, the image +// built for the same content by an earlier run, a promotion's among them, +// gets the commit's tag and nothing is built (crane, logged in to the +// registry by the job). Where it lacks it, the image is built and pushed +// under both tags (build.ts says how). An app from app-nextjs is built from +// its output, restored by the repo's own verb, `mise run build `, which +// the job runs against the trusted cache, where the app's e2e job left it; +// the directory is removed first, so that the image holds the restore and +// nothing a server or an earlier build wrote there. A miss builds the app, +// with the app's key, as the e2e job did. The output must hold +// apps//.next/BUILD_ID, the build's hash (generateBuildId in the +// template's next.config.ts), equal to the hash the image is tagged with: an +// output of another hash, or none where the Dockerfile's WORKDIR looks, is +// refused. The registry is the one place that says whether an image exists; +// publish records nothing else, and that the image was tested is the order of +// the jobs: a run's publish of an app follows that run's test and e2e jobs. +import { join } from 'node:path'; import type { Context } from '@plexus-ms/lib'; -import { run } from '@plexus-ms/lib'; -import { build } from './build.ts'; -import type { ImageContext } from './plan.ts'; +import { run, UsageError } from '@plexus-ms/lib'; +import { build, type ImageContext } from './build.ts'; import { craneDigest, imageName } from './registry.ts'; export interface PublishOptions { @@ -42,6 +51,38 @@ export interface Published { digest?: string; } +/** The output directory of an app from app-nextjs: the build context of its image. */ +const outputOf = (dir: string, app: string): string => join(dir, 'apps', app, '.next', 'standalone'); + +/** The output restored by the repo's verb into a clean directory, refused unless it is the build of `hash`. */ +async function restoreOutput(ctx: Context, options: PublishOptions): Promise { + const { app, dir, hash } = options; + const output = outputOf(dir, app); + await ctx.apply([ + run('rm', ['-rf', output]), + run('mise', ['run', 'build', app], { + cwd: dir, + env: { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey }, + }), + ]); + if (!ctx.dryRun) { + const where = `apps/${app}/.next/standalone`; + let id: string; + try { + id = (await ctx.readFile(join(output, 'apps', app, '.next', 'BUILD_ID'))).trim(); + } catch { + throw new Error( + `${where} holds no apps/${app}/.next/BUILD_ID: the build left no app at the place the Dockerfile starts it`, + ); + } + if (id !== hash) + throw new Error( + `${where} holds the build ${id}, not ${hash}: the plan and the build saw different inputs (another Turbo, or another PLX_PLATFORM)`, + ); + } + return output; +} + export async function publish(ctx: Context, options: PublishOptions): Promise { const { app, hash, sha } = options; const image = imageName(options.prefix, app); @@ -51,10 +92,12 @@ export async function publish(ctx: Context, options: PublishOptions): Promise` tags live: whether it holds a manifest, with -// crane, which the job has logged in to the registry. Nothing is started here. +// images and the `build-` tags live: whether it holds a manifest. The +// image helper asks with Docker's buildx, which it builds with and which +// reads Docker's login; the plan and the display versions ask with crane, +// which their job has logged in to the registry. Nothing is started here. import type { Context } from '@plexus-ms/lib'; import { ExecError, orAbsent } from '@plexus-ms/lib'; @@ -9,24 +11,50 @@ export const imageName = (prefix: string, app: string): string => `${prefix.toLo /** crane's answer that the registry holds no such manifest, or no such repository. */ const craneNotFound = (error: ExecError): boolean => /MANIFEST_UNKNOWN|NAME_UNKNOWN|\b404\b/.test(error.stderr); +/** buildx's answer that the registry holds no such manifest, or no such repository: `ERROR: : not found`. */ +const buildxNotFound = (error: ExecError): boolean => /: not found\s*$/m.test(error.stderr); + /** - * The digest of `ref` on a registry crane is logged in to, or undefined when - * the registry says it holds no such manifest. Any other failure is an error: - * a crane that cannot run or a login the registry refuses is the job's fault, - * and reporting it as a missing image sends the reader after a build that ran. - * Under --dry-run the failure is narrated and taken for absent, so a preview - * runs where there is no crane or no login. + * The digest of `ref`, or undefined when the registry says it holds no such + * manifest, asked by `command` with `args`. Any other failure is an error: a + * tool that cannot run or a login the registry refuses is the job's fault, + * and reporting it as a missing image sends the reader after a build that + * ran. Under --dry-run the failure is narrated and taken for absent, so a + * preview runs where there is no tool or no login. */ -export async function craneDigest(ctx: Context, ref: string): Promise { +async function digestOf( + ctx: Context, + ref: string, + command: string, + args: string[], + notFound: (error: ExecError) => boolean, + digest: (answer: string) => string | undefined, +): Promise { try { - return (await orAbsent(ctx.read('crane', ['digest', ref]), craneNotFound))?.trim() || undefined; + const answer = await orAbsent(ctx.read(command, args), notFound); + return answer === undefined ? undefined : digest(answer); } catch (error) { const why = error instanceof ExecError ? `could not look up ${ref}: ${error.message}` - : `crane could not run to look up ${ref}; is it installed in this job?`; + : `${command} could not run to look up ${ref}; is it installed in this job?`; if (!ctx.dryRun) throw new Error(why, { cause: error }); ctx.say(`[dry-run] ${why.split('\n')[0]}; taken for absent`); return undefined; } } + +/** The digest of `ref` as crane sees it, logged in by the job. */ +export const craneDigest = (ctx: Context, ref: string): Promise => + digestOf(ctx, ref, 'crane', ['digest', ref], craneNotFound, (answer) => answer.trim() || undefined); + +/** The digest of `ref` as Docker's buildx sees it, with Docker's login. */ +export const imageDigest = (ctx: Context, ref: string): Promise => + digestOf( + ctx, + ref, + 'docker', + ['buildx', 'imagetools', 'inspect', '--format', '{{json .Manifest}}', ref], + buildxNotFound, + (answer) => (JSON.parse(answer) as { digest?: string }).digest || undefined, + ); From 4bac6a61ede4f2785fcda0cf87d0bb640a7dbdaa Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:32:30 +0100 Subject: [PATCH 6/9] test: plx-ci has no image name of its own; the rule is imageRef of @plexus-ms/lib (PLX-225) What the removed test held, the prefix lower-cased and without its trailing slash, the tests of plx-ci image hold through the command, with IMAGE_PREFIX registry.example/Acme/. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/core/registry.test.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/cli-ci/src/core/registry.test.ts b/packages/cli-ci/src/core/registry.test.ts index 76d966a..859de2c 100644 --- a/packages/cli-ci/src/core/registry.test.ts +++ b/packages/cli-ci/src/core/registry.test.ts @@ -2,11 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context, ExecError } from '@plexus-ms/lib'; import { fakeIo, notThere } from '../testing/fakeIo.ts'; -import { craneDigest, imageName } from './registry.ts'; - -test('an image name is the prefix, lower-cased, and the app', () => { - assert.equal(imageName('ghcr.io/Plexus-MS-Tenant/', 'website'), 'ghcr.io/plexus-ms-tenant/website'); -}); +import { craneDigest } from './registry.ts'; test('craneDigest answers the digest, or undefined where the registry holds no such manifest', async () => { const io = fakeIo({}, undefined, { From f9edd6e181282ddcd3ca0c2a7b5114220e6d55e8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:32:59 +0100 Subject: [PATCH 7/9] plx-ci: the image's name and where the images live from @plexus-ms/lib alone imageRef and imagePrefix of lib are the one statement of the naming rule; plx-ci's own imageName, imagePrefix and ownerOf go, and plan, display-versions and publish take lib's. Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/displayVersions.ts | 6 +++--- packages/cli-ci/src/commands/plan.ts | 6 +++--- packages/cli-ci/src/commands/publish.ts | 4 ++-- packages/cli-ci/src/commands/shared.ts | 8 -------- packages/cli-ci/src/core/displayVersions.ts | 12 ++++++------ packages/cli-ci/src/core/plan.ts | 8 ++++---- packages/cli-ci/src/core/publish.ts | 15 ++++++++++----- packages/cli-ci/src/core/registry.ts | 2 -- 8 files changed, 28 insertions(+), 33 deletions(-) diff --git a/packages/cli-ci/src/commands/displayVersions.ts b/packages/cli-ci/src/commands/displayVersions.ts index fcb2367..b2f7541 100644 --- a/packages/cli-ci/src/commands/displayVersions.ts +++ b/packages/cli-ci/src/commands/displayVersions.ts @@ -20,11 +20,11 @@ // plx-ci tag-display-version 1.4 "$GITHUB_SHA" import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; -import { UsageError } from '@plexus-ms/lib'; +import { imagePrefix, UsageError } from '@plexus-ms/lib'; import type { Command } from 'commander'; import { displayVersions, tagDisplayVersion } from '../core/displayVersions.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix, need } from './shared.ts'; +import { need } from './shared.ts'; /** The app names of _e2e.yml's output `deploys`. */ export function appsOfDeploys(json: string): string[] { @@ -57,7 +57,7 @@ export function register(program: Command): void { environment, sha, apps: appsOfDeploys(opts.deploys), - prefix: imagePrefix(), + prefix: imagePrefix(process.env), }); ctx.result(result, (r) => [ diff --git a/packages/cli-ci/src/commands/plan.ts b/packages/cli-ci/src/commands/plan.ts index a610280..60639da 100644 --- a/packages/cli-ci/src/commands/plan.ts +++ b/packages/cli-ci/src/commands/plan.ts @@ -22,11 +22,11 @@ // plx-ci plan --deploy --inventory operations/inventory import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; -import { environmentOf, readDeployTargets, targetsIn } from '@plexus-ms/lib'; +import { environmentOf, imagePrefix, readDeployTargets, targetsIn } from '@plexus-ms/lib'; import type { Command } from 'commander'; import { appsOf, outputsOf, plan, readHashes } from '../core/plan.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix, need, settings, withStrategy } from './shared.ts'; +import { need, settings, withStrategy } from './shared.ts'; interface Opts { strategy?: string; @@ -62,7 +62,7 @@ export function register(program: Command): void { apps: all, hashes, strategy: s.strategy, - prefix: imagePrefix(), + prefix: imagePrefix(process.env), // Only hybrid names anything after the run: its instances. run: s.strategy === 'hybrid' diff --git a/packages/cli-ci/src/commands/publish.ts b/packages/cli-ci/src/commands/publish.ts index 104ffc3..ec6c934 100644 --- a/packages/cli-ci/src/commands/publish.ts +++ b/packages/cli-ci/src/commands/publish.ts @@ -18,12 +18,12 @@ // plx-ci publish website 0f2a3f35123dfd73 "$GITHUB_SHA" --context output import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; +import { imagePrefix } from '@plexus-ms/lib'; import type { Command } from 'commander'; import { Option } from 'commander'; import type { ImageContext } from '../core/build.ts'; import { publish } from '../core/publish.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix } from './shared.ts'; export function register(program: Command): void { program @@ -54,7 +54,7 @@ export function register(program: Command): void { app, hash, sha, - prefix: imagePrefix(), + prefix: imagePrefix(process.env), dir: resolve(opts.dir), context: opts.context, encryptionKey: env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ?? '', diff --git a/packages/cli-ci/src/commands/shared.ts b/packages/cli-ci/src/commands/shared.ts index e753fba..313a37f 100644 --- a/packages/cli-ci/src/commands/shared.ts +++ b/packages/cli-ci/src/commands/shared.ts @@ -33,9 +33,6 @@ export function githubOf(ctx: Context, env: NodeJS.ProcessEnv = process.env): Gi return env.RUNNER_TOKEN ? new GitHubRunners(ctx, need('GITHUB_REPOSITORY', env), env.RUNNER_TOKEN) : undefined; } -/** The owner of the repo, the default prefix of the image names. */ -export const ownerOf = (repo: string): string => repo.split('/')[0] ?? repo; - /** The option every universal command takes; the environment answers without it. */ export function withStrategy(command: Command): Command { return command.option('--strategy ', 'github, on-prem or hybrid (default: CI_STRATEGY, else github)'); @@ -45,8 +42,3 @@ export function withStrategy(command: Command): Command { export function settings(opts: { strategy?: string }, env: NodeJS.ProcessEnv = process.env): Settings { return settingsOf(env, opts.strategy); } - -/** Where the published images live: IMAGE_PREFIX, else ghcr.io/. */ -export function imagePrefix(env: NodeJS.ProcessEnv = process.env): string { - return env.IMAGE_PREFIX || `ghcr.io/${ownerOf(need('GITHUB_REPOSITORY', env))}`; -} diff --git a/packages/cli-ci/src/core/displayVersions.ts b/packages/cli-ci/src/core/displayVersions.ts index 81bbac5..8a62571 100644 --- a/packages/cli-ci/src/core/displayVersions.ts +++ b/packages/cli-ci/src/core/displayVersions.ts @@ -43,8 +43,8 @@ // first push and not at its first production release. The tag itself, with // its GitHub Release, is made by `tagDisplayVersion` once every deploy of the // release is green. -import { type Context, MARKER_FILE, splitFrontmatter, UsageError } from '@plexus-ms/lib'; -import { craneDigest, imageName } from './registry.ts'; +import { type Context, imageRef, MARKER_FILE, splitFrontmatter, UsageError } from '@plexus-ms/lib'; +import { craneDigest } from './registry.ts'; /** The environment whose releases cut versions. */ export const PRODUCTION = 'production'; @@ -147,10 +147,10 @@ export async function displayVersions(ctx: Context, options: DisplayVersionsOpti const changed: string[] = []; for (const app of apps) { - const image = imageName(prefix, app); - const current = await craneDigest(ctx, `${image}:${sha}`); - if (current === undefined && !ctx.dryRun) throw new Error(`${image}:${sha} is not published; publish runs first`); - const before = lastCommit ? await craneDigest(ctx, `${image}:${lastCommit}`) : undefined; + const ref = imageRef(prefix, app, sha); + const current = await craneDigest(ctx, ref); + if (current === undefined && !ctx.dryRun) throw new Error(`${ref} is not published; publish runs first`); + const before = lastCommit ? await craneDigest(ctx, imageRef(prefix, app, lastCommit)) : undefined; const same = before !== undefined && before === current; ctx.say(`${app}: ${same ? `unchanged since ${last?.tag}` : 'changed since the last version'}`); if (!same) changed.push(app); diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index 0588dd2..63c0d79 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -57,9 +57,9 @@ // app's build hash). Without PLX_PLATFORM the plan refuses: its hash would be // one no build ever has. import type { Context, EnvironmentTargets } from '@plexus-ms/lib'; -import { ExecError, MARKER_FILE, parseMarkerConfig, run as step, UsageError, write } from '@plexus-ms/lib'; +import { ExecError, imageRef, MARKER_FILE, parseMarkerConfig, run as step, UsageError, write } from '@plexus-ms/lib'; import { type ImageContext, packageName, turboOf } from './build.ts'; -import { craneDigest, imageName } from './registry.ts'; +import { craneDigest } from './registry.ts'; import { runnerOf, type Strategy } from './strategy.ts'; /** Whether the trusted cache holds an app's build, and the e2e of every one of its suites (true where it has none). */ @@ -292,7 +292,7 @@ export function deployLegsOf( for (const app of apps) { const host = targets[app]; if (host === undefined) without.push(app); - else legs.push({ app, host, image: `${imageName(prefix, app)}:${sha}` }); + else legs.push({ app, host, image: imageRef(prefix, app, sha) }); } return { legs, without }; } @@ -322,7 +322,7 @@ export async function plan(ctx: Context, dir: string, options: PlanOptions): Pro const { apps, hashes, strategy, prefix, run } = options; const result: Plan = { legs: [], environment: options.deploy?.environment ?? '', deploys: [] }; for (const leg of legsOf(apps, hashes, strategy, run)) { - const ref = `${imageName(prefix, leg.app)}:build-${leg.hash}`; + const ref = imageRef(prefix, leg.app, `build-${leg.hash}`); const build = (await craneDigest(ctx, ref)) === undefined; ctx.say(`${leg.app}: ${ref} ${build ? 'is missing; publish builds it' : 'exists; publish tags it'}`); const context = await imageContextOf(ctx, dir, leg.app); diff --git a/packages/cli-ci/src/core/publish.ts b/packages/cli-ci/src/core/publish.ts index f2ea7fc..15b3aec 100644 --- a/packages/cli-ci/src/core/publish.ts +++ b/packages/cli-ci/src/core/publish.ts @@ -18,9 +18,9 @@ // the jobs: a run's publish of an app follows that run's test and e2e jobs. import { join } from 'node:path'; import type { Context } from '@plexus-ms/lib'; -import { run, UsageError } from '@plexus-ms/lib'; +import { imageRef, run, UsageError } from '@plexus-ms/lib'; import { build, type ImageContext } from './build.ts'; -import { craneDigest, imageName } from './registry.ts'; +import { craneDigest } from './registry.ts'; export interface PublishOptions { app: string; @@ -85,8 +85,8 @@ async function restoreOutput(ctx: Context, options: PublishOptions): Promise { const { app, hash, sha } = options; - const image = imageName(options.prefix, app); - const target = `${image}:build-${hash}`; + const target = imageRef(options.prefix, app, `build-${hash}`); + const image = target.slice(0, target.lastIndexOf(':')); if ((await craneDigest(ctx, target)) !== undefined) { ctx.say(`publish: ${target} is there already, tagging it ${sha}`); await ctx.apply([run('crane', ['tag', target, sha])]); @@ -98,6 +98,11 @@ export async function publish(ctx: Context, options: PublishOptions): Promise `${prefix.toLowerCase().replace(/\/$/, '')}/${app}`; - /** crane's answer that the registry holds no such manifest, or no such repository. */ const craneNotFound = (error: ExecError): boolean => /MANIFEST_UNKNOWN|NAME_UNKNOWN|\b404\b/.test(error.stderr); From 7b5f1969417e5a9941b5f6b611df9d67d3e8cfae Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:33:56 +0100 Subject: [PATCH 8/9] test: an app from app-nextjs publishes through plx-ci image, pushing once and then only tagging (PLX-225) Co-Authored-By: Claude Opus 5.5 --- newborns/app-nextjs.test.ts | 45 +++++++++++++++++++++++++++++- packages/lib/src/appNextjs.test.ts | 13 ++++++++- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index d154f07..770eb87 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -10,13 +10,16 @@ // what the build task's cache holds. The image built from that directory alone // holds it and nothing else, and becomes healthy under the app's compose file, // a stateful app migrated first from what the directory holds; that needs docker. +// The repo's `publish` pushes that image to a registry on loopback under +// build- and the commit, and after a commit that changes no input of the +// build only adds the new commit's tag to it; that needs docker too. import assert from 'node:assert/strict'; import { randomBytes } from 'node:crypto'; import { cpSync, existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { born, close, freePort, open, pass, plxNew, put, relock, sh, start, tryRun } from './helpers.ts'; +import { born, close, freePort, git, open, pass, plxNew, put, relock, sh, start, tryRun } from './helpers.ts'; let here = ''; let repo = ''; @@ -260,6 +263,46 @@ for (const profile of PROFILES) { }); } +test("publish pushes the image of the app's output under build- and the commit, and a commit that changes no input of the build only tags it", async () => { + // The forge's registry: one on loopback, and a Docker config of the test's own, which holds no login. + const limits = ['--cpus', '4', '--memory', '6g', '--pids-limit', '1000']; + const started = await sh('docker', ['run', '-d', '--rm', ...limits, '-p', '127.0.0.1::5000', 'registry:2'], here); + const container = /^[0-9a-f]{64}$/m.exec(started)?.[0] ?? ''; + assert.ok(container, started); + const registry = (await sh('docker', ['port', container, '5000/tcp'], here)).trim().split('\n')[0] ?? ''; + const env = { IMAGE_PREFIX: `${registry}/acme`, DOCKER_CONFIG: join(here, 'docker-config') }; + put(here, { 'docker-config/config.json': {} }); + const digest = async (ref: string) => + JSON.parse( + await sh('docker', ['buildx', 'imagetools', 'inspect', '--format', '{{json .Manifest}}', ref], here, env), + ).digest as string; + const commit = async (...args: string[]) => { + const ran = await git(repo, 'commit', '-q', '--no-verify', ...args); + assert.ok(ran.ok, ran.output); + return (await sh('git', ['rev-parse', 'HEAD'], repo)).trim(); + }; + try { + const first = await commit('-m', 'the app'); + const pushed = await tryRun('mise', ['run', 'publish', 'stateless'], repo, env); + assert.ok(pushed.ok, pushed.output); + const { build } = await hashes('stateless'); + const image = `${registry}/acme/stateless`; + assert.match(pushed.output, new RegExp(`${image}:build-${build} is missing, building it from the build output`)); + const built = await digest(`${image}:build-${build}`); + assert.equal(await digest(`${image}:${first}`), built); + + const second = await commit('--allow-empty', '-m', 'nothing the build reads'); + const tagged = await tryRun('mise', ['run', 'publish', 'stateless'], repo, env); + assert.ok(tagged.ok, tagged.output); + assert.match(tagged.output, new RegExp(`${image}:build-${build} is there already, tagging it ${second}`)); + assert.doesNotMatch(tagged.output, /buildx build|building it/); + assert.equal(await digest(`${image}:${second}`), built); + } finally { + await tryRun('docker', ['rm', '-f', container], here); + await tryRun('sh', ['-c', `docker image ls -q '${registry}/acme/stateless' | xargs -r docker image rm -f`], here); + } +}); + test('the repo around the apps passes its own test, which includes check', async () => { await pass(repo, 'acme', 'test'); }); diff --git a/packages/lib/src/appNextjs.test.ts b/packages/lib/src/appNextjs.test.ts index 3a0c59d..2505be2 100644 --- a/packages/lib/src/appNextjs.test.ts +++ b/packages/lib/src/appNextjs.test.ts @@ -85,12 +85,23 @@ test('the source an author edits and the marker are written once, the rest is me test('the marker names the verbs an app has, what its test script runs, and what its build leaves', async () => { const marker = textOf(await render(), 'PLEXUS.md'); - for (const verb of ['dev', 'build', 'check', 'test', 'e2e']) assert.match(marker, new RegExp(`mise :${verb} `)); + for (const verb of ['dev', 'build', 'check', 'test', 'e2e', 'publish']) + assert.match(marker, new RegExp(`mise :${verb} `)); assert.doesNotMatch(marker, /verify/); assert.match(marker, /`node --test`.*\*\*\/\*\.test\.\{cts,mts,ts\}/); assert.match(marker, /static files and `public\/`/); }); +test('the publish script calls the image helper of plx-ci, and nothing else', async () => { + for (const profile of ['stateless', 'stateful']) + assert.equal( + JSON.parse(textOf(await render({ profile }), 'package.json')).scripts.publish, + 'plx-ci image', + profile, + ); + assert.match(textOf(await render(), 'PLEXUS.md'), /`publish` script.*`plx-ci image`/); +}); + test('the marker has no frontmatter, which plx writes', async () => { assert.ok(!textOf(await render({ profile: 'stateful' }), 'PLEXUS.md').startsWith('---')); }); From fe952eaaf4f81c292ce754fe047c1a316b62f056 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Wed, 2 Dec 2026 04:35:14 +0100 Subject: [PATCH 9/9] app-nextjs: a publish script, plx-ci image, and the marker naming it Co-Authored-By: Claude Opus 5.5 --- templates/app-nextjs/files/PLEXUS.md.jinja | 3 ++- templates/app-nextjs/files/package.json.jinja | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/templates/app-nextjs/files/PLEXUS.md.jinja b/templates/app-nextjs/files/PLEXUS.md.jinja index 030f7fd..1c65306 100644 --- a/templates/app-nextjs/files/PLEXUS.md.jinja +++ b/templates/app-nextjs/files/PLEXUS.md.jinja @@ -1,6 +1,7 @@ - `{{ name }}`, a Next.js app: its `build` leaves one directory that runs as it is, `.next/standalone`, `docker/Dockerfile` copies that directory into its image, and `docker/compose.yaml` runs the image on its host. - The `build` script completes Next's standalone output in place: after `next build` it copies the static files and `public/` into it, as Next's documentation of `output: 'standalone'` describes. -- Its verbs are the repo root's: `mise :dev `, `mise :build `, `mise :check `, `mise :test ` and `mise :e2e `, `` being this directory's name. +- Its verbs are the repo root's: `mise :dev `, `mise :build `, `mise :check `, `mise :test `, `mise :e2e ` and `mise :publish `, `` being this directory's name. +- The `publish` script is `plx-ci image`: it pushes the image of the build output under the build's hash and the commit, or adds the commit's tag where the image of that hash is in the registry already. - The `test` script is `node --test`, which runs the files of Node's rule, `**/*.test.{cts,mts,ts}`, `**/*-test.{cts,mts,ts}`, `**/*_test.{cts,mts,ts}`, `**/test-*.{cts,mts,ts}`, `**/test.{cts,mts,ts}` and `**/test/**/*.{cts,mts,ts}` and their `.cjs`, `.mjs` and `.js` siblings, with relative imports: no `.tsx` file runs, and no `@/` import resolves. An app with such tests names its own runner in that script. {%- if profile == 'stateful' %} diff --git a/templates/app-nextjs/files/package.json.jinja b/templates/app-nextjs/files/package.json.jinja index b689ea7..d6b1cf9 100644 --- a/templates/app-nextjs/files/package.json.jinja +++ b/templates/app-nextjs/files/package.json.jinja @@ -6,7 +6,8 @@ "dev": "next dev", "build": "next build && out=.next/standalone/$(node -p \"require('./.next/required-server-files.json').relativeAppDir\") && cp -R .next/static \"$out/.next/\" && if [ -d public ]; then cp -R public \"$out/\"; fi", "check": "next typegen && tsc --noEmit", - "test": "node --test"{% if profile == 'stateful' %}, + "test": "node --test", + "publish": "plx-ci image"{% if profile == 'stateful' %}, "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the directory the build leaves, so the build puts in that directory whatever the command needs (outputFileTracingIncludes in next.config.ts, or the build script).' >&2; exit 1", "seed": "echo 'seed: not written yet. Name the command here that loads development sample data into a fresh, migrated database.' >&2; exit 1"{% endif %} },