stock-bot/scripts/package-candidate-strategy.ts

88 lines
3.1 KiB
TypeScript

/** Candidate TypeScript transformation occurs only in the pinned OS sandbox.
* CLI: bun scripts/package-candidate-strategy.ts metadata.json strategy.ts > package.json
* Metadata supplies program/parameterSchema/execution/source. No dependency install or code evaluation. */
import { createHash, randomUUID } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { z } from 'zod';
import type { StrategyVersionPackage } from '@stock-bot/types';
import { candidatePackageExecutionSchema } from '../apps/stock/config/src/contracts/candidate-execution';
import {
assertStrategyJsonText,
parseStrategyVersionPackage,
} from '../apps/stock/config/src/contracts/strategy';
import { IsolatedCandidateController } from '../apps/stock/orchestrator/src/backtest/candidate-sandbox';
const hash = (value: string) => createHash('sha256').update(value, 'utf8').digest('hex');
/** This function reads source as data; the container owns the TS compiler. Computed/eval imports
* cannot be proven absent by static scanning; runtime OS isolation remains authoritative. */
export async function packageCandidateStrategy(
metadata: unknown,
source: string
): Promise<StrategyVersionPackage> {
assertStrategyJsonText(metadata);
const raw = z
.object({
program: z.unknown(),
parameterSchema: z.unknown(),
execution: candidatePackageExecutionSchema,
source: z.unknown(),
entryExport: z.string().regex(/^[A-Za-z_$][\w$]*$/),
})
.strict()
.parse(metadata);
// Validate inert declarations before allocating an isolated process.
const dependencyLock = await readFile(
fileURLToPath(new URL('../bun.lock', import.meta.url)),
'utf8'
);
const preliminary = parseStrategyVersionPackage({
version: 1,
program: raw.program,
parameterSchema: raw.parameterSchema,
execution: raw.execution,
source: raw.source,
artifact: {
format: 'esm-bundle/v1',
entryExport: raw.entryExport,
content: source,
sha256: hash(source),
},
dependencyLock: {
format: 'bun-lock/v1',
content: dependencyLock,
sha256: hash(dependencyLock),
},
build: { tool: 'bun', version: Bun.version, target: 'browser' },
});
const transformed = await IsolatedCandidateController.transpile(
source,
`stock-bot-candidate-${randomUUID()}`
);
return parseStrategyVersionPackage({
...preliminary,
artifact: {
...preliminary.artifact,
content: transformed.content,
sha256: hash(transformed.content),
},
build: { tool: 'bun', version: transformed.runtimeVersion, target: 'browser' },
});
}
if (import.meta.main) {
const [metadataPath, sourcePath, ...extra] = process.argv.slice(2);
if (!metadataPath || !sourcePath || extra.length) {
throw new Error('Usage: package-candidate-strategy.ts metadata.json strategy.ts');
}
console.log(
JSON.stringify(
await packageCandidateStrategy(
JSON.parse(await readFile(resolve(metadataPath), 'utf8')),
await readFile(resolve(sourcePath), 'utf8')
),
null,
2
)
);
}