stock-bot/scripts/test/library-boundaries.test.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
2026-11-27 00:11:50 -05:00

214 lines
7.9 KiB
TypeScript

import { readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import * as utils from '@stock-bot/utils';
import { fetch } from '@stock-bot/utils/fetch';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import { checks } from '../check';
import { runtimeImports } from '../runtime-imports';
const root = fileURLToPath(new URL('../../', import.meta.url));
const utilsRoot = join(root, 'libs/utils');
const manifest = JSON.parse(readFileSync(join(utilsRoot, 'package.json'), 'utf8'));
const sourceFiles = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: utilsRoot })].map(file =>
join(utilsRoot, file)
);
describe('shared library boundaries', () => {
it('utils exposes general helpers without a financial framework', () => {
expect(Object.keys(utils).sort()).toEqual([
'fetch',
'getRandomUserAgent',
]);
expect(utils.fetch).toBe(fetch);
expect(utils.getRandomUserAgent).toBe(getRandomUserAgent);
expect(manifest.private).toBe(true);
expect(manifest.exports).toEqual({
'.': './src/index.ts',
'./fetch': './src/fetch.ts',
'./user-agent': './src/user-agent.ts',
});
for (const retired of ['assertions', 'calculations', 'common', 'dates', 'src/fetch', 'dateUtils']) {
expect(() => Bun.resolveSync(`@stock-bot/utils/${retired}`, root)).toThrow();
}
});
it('utils cannot load infrastructure adapters or grow another domain-math API', () => {
expect(Object.keys(manifest.dependencies).sort()).toEqual([
'@stock-bot/invariants',
'@stock-bot/logger',
]);
const config = JSON.parse(readFileSync(join(utilsRoot, 'tsconfig.json'), 'utf8'));
expect(config.references.map((ref: { path: string }) => ref.path).sort()).toEqual([
'../core/invariants',
'../core/logger',
]);
for (const file of sourceFiles) {
expect(file).not.toContain('/calculations/');
for (const specifier of runtimeImports(file)) {
if (specifier.startsWith('.')) {
const local = resolve(dirname(file), specifier);
expect(
sourceFiles.some(
target => target === `${local}.ts` || target === join(local, 'index.ts')
)
).toBe(true);
} else {
// Logger is a type-only capability; only invariants may be loaded at runtime.
expect(specifier).toBe('@stock-bot/invariants');
}
}
}
});
it('calculations is a portable pure library, with legacy code isolated from supported exports', () => {
const directory = join(root, 'libs/calculations');
const pkg = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
expect(Object.keys(pkg.dependencies).sort()).toEqual([
'@stock-bot/invariants',
'@stock-bot/types',
]);
expect(pkg.private).toBe(true);
const sources = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: directory })].map(file =>
join(directory, file)
);
for (const file of sources) {
for (const specifier of runtimeImports(file)) {
if (!specifier.startsWith('.')) {
expect(specifier).toBe('@stock-bot/invariants');
continue;
}
const target = resolve(dirname(file), specifier);
const dependency = sources.find(
source => source === `${target}.ts` || source === join(target, 'index.ts')
);
expect(dependency).toBeDefined();
if (!file.includes('/legacy/')) expect(dependency).not.toContain('/legacy/');
}
}
expect(Object.keys(pkg.exports).sort()).toEqual([
'.',
'./analytics',
'./indicators',
'./market-data',
'./returns',
]);
for (const path of [
'legacy',
'research',
'src/legacy/basic-calculations',
'legacy/technical-indicators',
]) {
expect(() => Bun.resolveSync(`@stock-bot/calculations/${path}`, root)).toThrow();
}
expect(runtimeImports(join(root, 'libs/core/invariants/src/index.ts'))).toEqual([]);
});
it('stock applications use reviewed calculation contracts, not archived prototypes or legacy math', () => {
const directory = join(root, 'apps/stock');
const files = [...new Bun.Glob('*/src/**/*.ts').scanSync({ cwd: directory })];
for (const file of files) {
for (const specifier of runtimeImports(join(directory, file))) {
expect(specifier).not.toMatch(/^@stock-bot\/calculations\/(legacy|research)/);
if (specifier.startsWith('.')) {
const target = resolve(dirname(join(directory, file)), specifier);
expect(target).not.toContain('/libs/calculations/src/legacy/');
expect(target).not.toContain('/libs/calculations/research/');
}
}
}
});
it('chart indicator adapters can be bundled for browsers without native or server dependencies', async () => {
const file = join(root, 'apps/stock/web-app/src/features/charts/utils/indicators.ts');
expect(runtimeImports(file).sort()).toEqual([
'@stock-bot/calculations/indicators',
'@stock-bot/calculations/market-data',
'@stock-bot/invariants',
]);
const bundle = await Bun.build({ entrypoints: [file], target: 'browser', write: false });
expect(bundle.success).toBe(true);
const code = await bundle.outputs[0]?.text();
expect(code).toBeDefined();
expect(code).not.toContain('engine.node');
expect(code).not.toContain('PostgresClient');
expect(code).not.toContain('legacy/technical-indicators');
});
it('library source and tests contain no disabled or backup copies', () => {
const files = [...new Bun.Glob('**/*').scanSync({ cwd: join(root, 'libs') })];
const backups = files.filter(
file =>
!file.split('/').some(part => ['node_modules', 'dist'].includes(part)) &&
/\.(old|disabled|bak|orig)$/.test(file)
);
expect(backups).toEqual([]);
});
it('the root gate runs utility and HTTP-consumer regressions', () => {
expect(checks).toContain('test:utils');
expect(checks).toContain('test:calculations');
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
expect(pkg.scripts['test:utils']).toBe(
'bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts'
);
for (const path of ['apps/stock/orchestrator', 'tools/coverage-cli']) {
const consumer = JSON.parse(readFileSync(join(root, path, 'package.json'), 'utf8'));
expect(consumer.dependencies).not.toHaveProperty('@stock-bot/utils');
expect(consumer.dependencies).not.toHaveProperty('simple-statistics');
}
});
});
describe('runtime dependency inspection', () => {
it('ignores erased type-only imports and re-exports', () => {
expect(
runtimeImports(
'fixture.ts',
`
import type { Logger } from 'logger';
import { type Cache } from 'cache';
import type * as DB from 'database';
export type { Portfolio } from 'finance';
export { type Model } from 'models';
type Lazy = typeof import('type-query');
import type Legacy = require('legacy-type');
`
)
).toEqual([]);
});
it('detects static, mixed, side-effect, lazy and CommonJS runtime edges', () => {
expect(
runtimeImports(
'fixture.ts',
`
import { run, type Options } from 'mixed';
import fallback, { type Shape } from 'default';
import 'side-effect';
export { execute, type Input } from 're-export';
export * from 'star';
export * as ns from 'namespace';
import {} from 'empty-import';
export {} from 'empty-export';
const module = await import('lazy');
const cjs = require('commonjs');
import legacy = require('import-equals');
`
)
).toEqual([
'mixed',
'default',
'side-effect',
're-export',
'star',
'namespace',
'empty-import',
'empty-export',
'lazy',
'commonjs',
'import-equals',
]);
});
});