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([ 'createProxyUrl', 'dateUtils', 'fetch', 'getRandomUserAgent', 'sleep', 'utcDates', ]); 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', './common': './src/common.ts', './dates': './src/dateUtils.ts', }); for (const retired of ['assertions', 'calculations', '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', './legacy', './market-data', './returns', ]); for (const path of [ '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', ]); }); });