#!/usr/bin/env node // Explicit advanced producer. The resulting bundle uses the ordinary document-first apply path. import { mkdirSync, mkdtempSync, realpathSync, existsSync, readFileSync, rmSync, copyFileSync, chmodSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { parse } from 'yaml'; import { prepareBundle } from './release-bundle.mjs'; import { commandRunner } from './publish-installation.mjs'; import { dockerHub } from './release-registry.mjs'; const repositoryRoot = resolve(import.meta.dirname, '../..'); export function sourceOptions(args) { const values = {}; for (let i = 0; i < args.length; i += 2) { if (!['--revision', '--version', '--platform', '--output'].includes(args[i]) || !args[i + 1] || values[args[i]]) throw new Error('Use --revision COMMIT --version VERSION --platform linux/amd64|linux/arm64 --output NEW_DIRECTORY.'); values[args[i]] = args[i + 1]; } if (!values['--revision'] || values['--revision'].startsWith('-') || !/^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$/.test(values['--version'] ?? '') || !['linux/amd64', 'linux/arm64'].includes(values['--platform']) || !values['--output']) throw new Error('Select an explicit source revision, version, Linux platform and new output directory.'); return { revision: values['--revision'], version: values['--version'], platform: values['--platform'], output: resolve(values['--output']) }; } export async function buildSourceImages({ run, source, output, revision, version, platform }) { const images = {}; for (const role of ['core', 'frontend']) { const iid = join(output, `${role}.iid`); await run('docker', ['buildx', 'build', '--load', '--platform', platform, '--file', `docker/${role}.Dockerfile`, '--iidfile', iid, '--build-arg', `IMAGE_VERSION=${version}`, '--label', `org.opencontainers.image.revision=${revision}`, '--label', `org.opencontainers.image.version=${version}`, '--provenance=false', '--sbom=false', '.'], { cwd: source, timeout: 45 * 60_000 }); const id = readFileSync(iid, 'utf8').trim(); if (!/^sha256:[a-f0-9]{64}$/.test(id)) throw new Error('Source build did not produce an immutable local image identity.'); const image = JSON.parse(await run('docker', ['image', 'inspect', '--format', '{{json .}}', id], { quiet: true })); if (image.Id !== id || `${image.Os}/${image.Architecture}` !== platform || image.Config?.Labels?.['org.opencontainers.image.revision'] !== revision || image.Config?.Labels?.['org.opencontainers.image.version'] !== version) throw new Error('Built image identity differs from the selected source.'); images[role] = id; } return images; } export async function prepareSourceInstallation(options) { // mkdir is exclusive: never replace a bundle or mix an incomplete previous build with new inputs. mkdirSync(options.output, { mode: 0o700 }); if (realpathSync(options.output) !== options.output) throw new Error('Use a canonical output path.'); const logs = join(options.output, 'logs'); mkdirSync(logs, { mode: 0o700 }); const run = commandRunner(logs); let temporary, source; try { const revision = (await run('git', ['rev-parse', '--verify', `${options.revision}^{commit}`], { quiet: true })).trim(); if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error('Select a committed source revision.'); await run('docker', ['info', '--format', '{{.OSType}}']); await run('docker', ['buildx', 'version']); temporary = realpathSync(mkdtempSync(join(tmpdir(), 'thothii-source-'))); source = join(temporary, 'source'); await run('git', ['worktree', 'add', '--detach', source, revision]); console.log(`Building explicit source installation ${revision} for ${options.platform}.`); const images = await buildSourceImages({ run, source, output: options.output, revision, version: options.version, platform: options.platform }); const compose = parse(readFileSync(join(source, 'compose.yaml'), 'utf8')); const registry = dockerHub(); for (const [role, service] of [['catalog', 'catalog-db'], ['qdrant', 'qdrant'], ['embedding', 'embedding']]) { const [name, digest] = compose.services[service].image.split('@'); if (!/^sha256:[a-f0-9]{64}$/.test(digest ?? '')) throw new Error('Upstream source images must already be pinned.'); let repository = name.replace(/:[^/:]+$/, '').replace(/^docker.io\//, ''); if (!repository.includes('/')) repository = `library/${repository}`; images[role] = (await registry.inspect(repository, digest, options.platform, { anonymous: true })).reference; } await run('npm', ['ci'], { cwd: join(source, 'backend'), timeout: 10 * 60_000 }); const target = options.platform.replace('/', '-'); const sourceTime = (await run('git', ['show', '-s', '--format=%cI', revision], { quiet: true })).trim(); await run(process.execPath, [join(repositoryRoot, 'backend/scripts/build-workspace-tools.mjs'), target], { cwd: join(source, 'backend'), env: { ...process.env, THT_BUILD_SOURCE_ROOT: source, THT_BUILD_VERSION: options.version, THT_BUILD_TIME: sourceTime }, timeout: 10 * 60_000, }); const bundle = join(options.output, 'bundle'); mkdirSync(bundle, { mode: 0o700 }); prepareBundle({ source, destination: bundle, platform: options.platform, version: options.version, revision, images, distribution: 'source' }); mkdirSync(join(bundle, 'bin')); for (const executable of ['tht', 'tht-workspace-documents']) { copyFileSync(join(source, 'dist/workspace-tools', target, executable), join(bundle, 'bin', executable)); chmodSync(join(bundle, 'bin', executable), 0o755); } await run('docker', ['compose', '-f', join(bundle, 'compose.yaml'), '-f', join(bundle, 'deploy/compose.local.yaml'), '--profile', 'catalog-maintenance', '--profile', 'workspace-maintenance', 'config', '--no-interpolate', '--no-env-resolution', '--format', 'json']); console.log(`Source bundle prepared: ${bundle}. Use its operator for ordinary installation validate, plan and apply on this Docker daemon.`); return bundle; } finally { if (source && existsSync(source)) await run('git', ['worktree', 'remove', '--force', source]).catch(() => {}); if (temporary && !existsSync(source ?? '')) rmSync(temporary, { recursive: true, force: true }); } } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { try { await prepareSourceInstallation(sourceOptions(process.argv.slice(2))); } catch { console.error('Source preparation failed. Inspect the private build logs and use a new output directory to retry; no images were published.'); process.exitCode = 1; } }