stock-bot/scripts/package-builtin-strategies.ts

188 lines
7.4 KiB
TypeScript

/** Offline compilation of the two reviewed canonical built-ins. No database,
* native engine, candidate module imports or runtime activation. */
import { createHash } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
import type { StrategyVersionPackage } from '@stock-bot/types';
import {
builtinCatalogDescriptors,
parseStrategyVersionPackage,
} from '../apps/stock/config/src/contracts/strategy';
const repositoryRoot = fileURLToPath(new URL('../', import.meta.url));
const entries = {
sma_crossover: 'apps/stock/orchestrator/src/strategies/canonical-sma.ts',
mean_reversion: 'apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts',
} as const;
// Workspace packages normally expose generated dist files. Packaging must read
// current source, including the pure config subpaths, without relying on those
// files having been rebuilt in the right order.
const workspaceSources: Record<string, string> = {
'@stock-bot/types': 'libs/core/types/src/index.ts',
'@stock-bot/invariants': 'libs/core/invariants/src/index.ts',
'@stock-bot/calculations': 'libs/calculations/src/index.ts',
'@stock-bot/calculations/indicators': 'libs/calculations/src/indicators/index.ts',
'@stock-bot/calculations/returns': 'libs/calculations/src/returns.ts',
'@stock-bot/stock-config/canonical-replay': 'apps/stock/config/src/contracts/canonical-replay.ts',
'@stock-bot/stock-config/strategy': 'apps/stock/config/src/contracts/strategy.ts',
'@stock-bot/stock-config/backtest': 'apps/stock/config/src/contracts/backtest.ts',
};
const sha256 = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
function git(root: string, args: string[]): string {
const result = Bun.spawnSync(['git', '-C', root, ...args], {
stdout: 'pipe',
stderr: 'pipe',
});
if (result.exitCode !== 0) {
throw new Error(`Cannot read packaging source identity: git ${args[0]} failed`);
}
return result.stdout.toString('utf8');
}
function assertSelfContained(content: string, entryExport: string): void {
const source = ts.createSourceFile(
'strategy.mjs',
content,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.JS
);
let exportsFactory = false;
function visit(node: ts.Node): void {
if (
ts.isExportDeclaration(node) &&
node.exportClause &&
ts.isNamedExports(node.exportClause) &&
node.exportClause.elements.some(element => element.name.text === entryExport)
) {
exportsFactory = true;
}
const imported =
ts.isImportDeclaration(node) ||
(ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined) ||
(ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference));
const loaded =
(ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) ||
(ts.isIdentifier(node) && /^(?:__)?require$/.test(node.text)) ||
(ts.isElementAccessExpression(node) &&
ts.isStringLiteral(node.argumentExpression) &&
node.argumentExpression.text === 'require');
if (imported || loaded) {
throw new Error('Strategy bundle contains an external import or require');
}
ts.forEachChild(node, visit);
}
visit(source);
if (!exportsFactory) {
throw new Error(`Strategy bundle does not export its declared factory: ${entryExport}`);
}
}
export async function packageBuiltinStrategies({
rootDir = repositoryRoot,
}: { rootDir?: string } = {}): Promise<StrategyVersionPackage[]> {
const root = resolve(rootDir);
const revision = git(root, ['rev-parse', '--verify', 'HEAD']).trim();
if (!/^[a-f0-9]{40,64}$/.test(revision)) {
throw new Error('Cannot read full Git source revision');
}
const dirtyBefore =
git(root, ['status', '--porcelain=v1', '--untracked-files=normal']).length > 0;
// Keep original lock bytes: parsing/stringifying Bun's JSONC lock would change
// the retained artifact even if dependency resolution remained equivalent.
const lockBytes = await readFile(resolve(root, 'bun.lock'));
const lockContent = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(lockBytes);
if (!Buffer.from(lockContent, 'utf8').equals(lockBytes)) {
throw new Error('Dependency lock must contain exact UTF-8 bytes');
}
const dependencyLock = {
format: 'bun-lock/v1' as const,
content: lockContent,
sha256: sha256(lockContent),
};
const packages: StrategyVersionPackage[] = [];
for (const descriptor of builtinCatalogDescriptors) {
const entry = entries[descriptor.program.strategyId as keyof typeof entries];
if (!entry) {
throw new Error(`No reviewed bundle entry for ${descriptor.program.strategyId}`);
}
const build = await Bun.build({
entrypoints: [resolve(root, entry)],
root,
target: 'browser',
format: 'esm',
packages: 'bundle',
splitting: false,
sourcemap: 'none',
minify: false,
env: 'disable',
plugins: [
{
name: 'reviewed-strategy-workspace-sources',
setup(builder) {
builder.onResolve({ filter: /^@stock-bot\// }, ({ path }) => {
const source = workspaceSources[path];
if (!source) {
throw new Error(`Unsupported strategy workspace dependency: ${path}`);
}
return { path: resolve(root, source) };
});
},
},
],
});
if (!build.success || build.outputs.length !== 1 || build.outputs[0]?.kind !== 'entry-point') {
throw new Error(
`Expected one self-contained strategy bundle for ${descriptor.program.strategyId}`
);
}
const content = await build.outputs[0].text();
assertSelfContained(content, descriptor.entryExport);
packages.push(
parseStrategyVersionPackage({
version: 1,
program: structuredClone(descriptor.program),
artifact: {
format: 'esm-bundle/v1',
entryExport: descriptor.entryExport,
content,
sha256: sha256(content),
},
dependencyLock: { ...dependencyLock },
parameterSchema: structuredClone(descriptor.parameterSchema),
source: { revision, dirty: dirtyBefore },
build: { tool: 'bun', version: Bun.version, target: 'browser' },
})
);
}
if (git(root, ['rev-parse', '--verify', 'HEAD']).trim() !== revision) {
throw new Error('Source revision changed during strategy packaging; retry');
}
const dirtyAfter = git(root, ['status', '--porcelain=v1', '--untracked-files=normal']).length > 0;
for (const entry of packages) {
entry.source.dirty = dirtyBefore || dirtyAfter;
}
return packages.map(parseStrategyVersionPackage);
}
if (import.meta.main) {
try {
const args = process.argv.slice(2);
if (args.length !== 2 || args[0] !== '--out' || !args[1]) {
throw new Error('Usage: bun run scripts/package-builtin-strategies.ts --out <path>');
}
const packages = await packageBuiltinStrategies();
const output = resolve(args[1]);
await mkdir(dirname(output), { recursive: true });
await writeFile(output, `${JSON.stringify({ version: 1, packages }, null, 2)}\n`, 'utf8');
process.stdout.write(`Packaged ${packages.length} reviewed built-ins to ${output}\n`);
} catch (error) {
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
process.exitCode = 1;
}
}