/**
 * Railway start-command pin helper.
 *
 * Owns the one place that knows how to format a Studiograph start command
 * and shove it onto a Railway service. Three callers existed before this
 * file: `studiograph deploy railway`, `studiograph redeploy`, and the web
 * agent's `redeploy_railway` tool. Each pinned the version independently;
 * `redeploy` swallowed pin failures and continued — see cli-owner-audit
 * §6.2 and the codex review appendix.
 *
 * Contract:
 *   - `pinStartCommand` throws on Railway API errors. Callers should NOT
 *     try/catch and continue: a failed pin means the deploy or redeploy
 *     will boot the wrong version. Fail loud.
 *   - The resolved start command string is returned so callers can log
 *     it (matches the existing UX from redeploy/deploy).
 *   - Version selection is the caller's responsibility — pass the exact
 *     version you want pinned. Today every caller reads it from
 *     `package.json`. The recommended invocation is
 *       npx -y studiograph@<exact-version> <command>
 *     which produces a CLI whose `package.json` already matches the npx
 *     version, eliminating the cli-version-pin footgun.
 *
 * `studiograph init` runs once on first boot when the workspace volume
 * is empty (the `deploy` command's start command threads it in); after
 * that, the start command is just `npx --yes studiograph@<v> serve`.
 * `pinStartCommand` overwrites whatever's there, so a redeploy after the
 * volume already has `.studiograph/workspace.json` correctly skips the
 * init guard inline.
 */
import { readFileSync } from 'fs';
const SERVICE_INSTANCE_UPDATE_MUTATION = `
  mutation($serviceId: String!, $environmentId: String!, $input: ServiceInstanceUpdateInput!) {
    serviceInstanceUpdate(serviceId: $serviceId, environmentId: $environmentId, input: $input)
  }
`;
/**
 * Set the Railway service's start command to the given Studiograph version.
 * Returns the resolved start command string.
 *
 * Throws if the Railway API returns an error. Callers must not swallow.
 */
export async function pinStartCommand(query, ctx, version, opts = {}) {
    const startCommand = opts.startCommand ?? `npx --yes studiograph@${version} serve`;
    await query(SERVICE_INSTANCE_UPDATE_MUTATION, {
        serviceId: ctx.serviceId,
        environmentId: ctx.environmentId,
        input: { startCommand },
    });
    return startCommand;
}
/**
 * Convenience: query the npm registry for the latest published `@next`
 * version of studiograph. Non-blocking — returns `null` on failure (network
 * blip, registry down, malformed response) so callers can log an
 * informational note without bailing.
 *
 * Used by `redeploy` to print "Heads up: @next is now X; you're pinning Y"
 * when the local CLI lags the published @next. Doesn't block redeploy —
 * the owner may be intentionally pinning an earlier tested version.
 */
export async function fetchLatestNextVersion(opts = {}) {
    const fetchFn = opts.fetchFn ?? fetch;
    const timeoutMs = opts.timeoutMs ?? 3000;
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);
    try {
        const res = await fetchFn('https://registry.npmjs.org/studiograph', {
            headers: { Accept: 'application/json' },
            signal: controller.signal,
        });
        if (!res.ok)
            return null;
        const json = (await res.json());
        return json['dist-tags']?.next ?? null;
    }
    catch {
        return null;
    }
    finally {
        clearTimeout(timer);
    }
}
/**
 * Read the running CLI's own package.json version. Centralized so callers
 * don't duplicate the `new URL('../../../package.json', import.meta.url)`
 * dance and pick up the same answer.
 */
export function readOwnVersion() {
    // Path is relative to this file's compiled location (dist/cli/railway-pin.js
    // → ../../package.json). The matching source-tree path is
    // src/cli/railway-pin.ts → ../../package.json (repo root). Both resolve.
    const pkgPath = new URL('../../package.json', import.meta.url);
    return JSON.parse(readFileSync(pkgPath, 'utf-8')).version;
}
//# sourceMappingURL=railway-pin.js.map