openclaw/scripts/openclaw-npm-prepublish-verify.ts
Peter Steinberger 062f88e3e3
refactor: extract reusable AI runtime package (#99059)
* refactor: extract reusable AI runtime package

* refactor: complete AI provider relocation

* refactor: keep llm core internal

* refactor(ai): make @openclaw/ai self-contained with host policy ports

Move pure transport helpers (tool projections, strict-schema normalization,
prompt-cache boundary, stream guards, anthropic/openai compat, request
activity) from src into packages/ai; move utf16-slice into
normalization-core. Inject host policy (guarded fetch, redaction,
strict-tool defaults, diagnostics logging) through AiTransportHost with
inert library defaults installed by src/llm/stream.ts. Narrow the public
barrel to instance-scoped createApiRegistry/createLlmRuntime; the
process-default runtime moves behind internal/ and
registerBuiltInApiProviders takes an explicit registry. Delete the
src/llm/api-registry re-export facade.

* fix(ai): teach node, jiti, and vite resolvers the @openclaw/ai and utf16-slice subpaths

The workspace alias tables in root-alias.cjs, plugin-sdk-native-resolver,
sdk-alias, the shared vitest config, and the Control UI vite config only
knew @openclaw/llm-core; Node-side plugin loading resolved @openclaw/ai
through the pnpm symlink to the unbuilt dist (checks-node-compact CI
failures), and the Control UI build broke on the new
normalization-core/utf16-slice subpath.

* chore(ui): drop leftover service-worker debug logging

* build(release): ship @openclaw/ai with its own shrinkwrap and honest dependency set

packages/ai declares only its six real runtime deps (kysely, chalk, json5,
tslog, zod, fs-safe, and proxyline were never imported); orphaned root deps
removed. generate-npm-shrinkwrap now treats publishable packages/* like
publishable plugins so the AI tarball pins its transitive tree even though
workspace deps are omitted from the root shrinkwrap. knip learns the
package entry points; the tsdown dts neverBundle option moves to its
documented deps.dts home; the README documents the no-semver internal/*
contract and host ports.

* docs(ai): add minimal external-consumer example app

examples/ai-chat consumes only the public @openclaw/ai surface (built dist
via the workspace link): isolated runtime, built-in provider registration,
one streamed completion. Supports Anthropic/OpenAI via env keys and a
keyless local Ollama target; live-verified against Ollama.

* docs(ai): document the @openclaw/ai package and workspace shrinkwrap boundary

* chore(check): include examples/ in duplicate-scan targets

* fix: emit normalization package subpaths

* fix: complete AI package boundary artifacts

* fix: align AI package boundary contracts

* fix(ci): stabilize package release contracts

* test: align documentation contract checks

* test: keep cron docs guard aligned

* test: align restored docs contract guards

* test: follow upstream docs contracts

* docs: drop superseded talk wording
2026-07-05 01:56:40 -04:00

146 lines
5.1 KiB
JavaScript

#!/usr/bin/env -S node --import tsx
// Openclaw Npm Prepublish Verify script supports OpenClaw repository automation.
import { mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { formatErrorMessage } from "../src/infra/errors.ts";
import { runNpmVerifyCommand } from "./lib/npm-verify-exec.ts";
import { runInstalledWorkspaceBootstrapSmoke } from "./lib/workspace-bootstrap-smoke.mjs";
import {
collectInstalledPackageErrors,
normalizeInstalledBinaryVersion,
resolveInstalledBinaryCommandInvocation,
} from "./openclaw-npm-postpublish-verify.ts";
import { resolveNpmCommandInvocation } from "./openclaw-npm-release-check.ts";
type InstalledPackageJson = {
version?: string;
};
export type OpenClawNpmPrepublishVerifyArgs =
| {
expectedVersion?: string;
dependencyTarballPaths: string[];
help: false;
tarballPath: string;
}
| {
expectedVersion?: undefined;
dependencyTarballPaths: [];
help: true;
tarballPath: "";
};
export function openClawNpmPrepublishVerifyUsage(): string {
return "Usage: node --import tsx scripts/openclaw-npm-prepublish-verify.ts <tarball.tgz> [expected-version] [dependency.tgz ...]";
}
export function parseOpenClawNpmPrepublishVerifyArgs(
argv: readonly string[],
): OpenClawNpmPrepublishVerifyArgs {
const args = argv[0] === "--" ? argv.slice(1) : argv;
const tarballPath = args[0]?.trim() ?? "";
if (tarballPath === "--help" || tarballPath === "-h") {
return { dependencyTarballPaths: [], help: true, tarballPath: "" };
}
if (!tarballPath) {
throw new Error(openClawNpmPrepublishVerifyUsage());
}
if (tarballPath.startsWith("-")) {
throw new Error(`Unknown openclaw npm prepublish verifier option: ${tarballPath}`);
}
const expectedVersion = args[1]?.trim();
if (expectedVersion?.startsWith("-")) {
throw new Error(`Unknown openclaw npm prepublish verifier option: ${expectedVersion}`);
}
const dependencyTarballPaths = args.slice(2).map((value) => value.trim());
const invalidDependency = dependencyTarballPaths.find(
(value) => value.length === 0 || value.startsWith("-"),
);
if (invalidDependency !== undefined) {
throw new Error(`Invalid dependency tarball path: ${invalidDependency || "<empty>"}`);
}
return expectedVersion
? { dependencyTarballPaths, expectedVersion, help: false, tarballPath }
: { dependencyTarballPaths, help: false, tarballPath };
}
function npmExec(args: string[], cwd: string): string {
const invocation = resolveNpmCommandInvocation({
npmArgs: args,
npmExecPath: process.env.npm_execpath,
nodeExecPath: process.execPath,
platform: process.platform,
});
return runNpmVerifyCommand(invocation, cwd);
}
function main(argv = process.argv.slice(2)): void {
const args = parseOpenClawNpmPrepublishVerifyArgs(argv);
if (args.help) {
console.log(openClawNpmPrepublishVerifyUsage());
return;
}
const workingDir = mkdtempSync(join(tmpdir(), "openclaw-prepublish-"));
const prefixDir = join(workingDir, "prefix");
try {
npmExec(
[
"install",
"-g",
"--prefix",
prefixDir,
...args.dependencyTarballPaths.map((dependency) => realpathSync(dependency)),
realpathSync(args.tarballPath),
"--no-fund",
"--no-audit",
],
workingDir,
);
const globalRoot = npmExec(["root", "-g", "--prefix", prefixDir], workingDir);
const packageRoot = join(globalRoot, "openclaw");
const pkg = JSON.parse(
readFileSync(join(packageRoot, "package.json"), "utf8"),
) as InstalledPackageJson;
const resolvedExpectedVersion = args.expectedVersion || pkg.version?.trim() || "";
const errors = collectInstalledPackageErrors({
expectedVersion: resolvedExpectedVersion,
installedVersion: pkg.version?.trim() ?? "",
packageRoot,
});
const binaryInvocation = resolveInstalledBinaryCommandInvocation(prefixDir, ["--version"]);
const installedBinaryVersion = runNpmVerifyCommand(binaryInvocation, workingDir);
if (normalizeInstalledBinaryVersion(installedBinaryVersion) !== resolvedExpectedVersion) {
errors.push(
`installed openclaw binary version mismatch: expected ${resolvedExpectedVersion}, found ${installedBinaryVersion || "<missing>"}.`,
);
}
if (errors.length === 0) {
runInstalledWorkspaceBootstrapSmoke({ packageRoot });
}
if (errors.length > 0) {
throw new Error(`prepared tarball install failed:\n- ${errors.join("\n- ")}`);
}
console.log(
`openclaw-npm-prepublish-verify: prepared tarball install OK (${resolvedExpectedVersion}).`,
);
} finally {
rmSync(workingDir, { force: true, recursive: true });
}
}
const entrypoint = process.argv[1] ? pathToFileURL(process.argv[1]).href : null;
if (entrypoint !== null && import.meta.url === entrypoint) {
try {
main();
} catch (error) {
console.error(`openclaw-npm-prepublish-verify: ${formatErrorMessage(error)}`);
process.exitCode = 1;
}
}