TypeScript, in layers, with a strict linter
The client was one main.js, one preload.js, three files in lib/ and one renderer
script. It is now a typed application whose imports point inward: domain (models,
ports, errors) knows nothing about Electron, Node or Python; application orchestrates
it through those ports; infrastructure holds the adapters — the Python CLI, HTTP, the
filesystem, Electron itself — and main, preload and renderer sit on top as hosts.
STRUCTURE.md is the map, and the deliverable as much as the code is: every layer, every
pattern in use (ports and adapters, repository vs gateway, service, DTO and mapper,
composition root, controller and router, single flight, observer streams, state store
with unidirectional flow, passive view, coded error hierarchy, frozen constant tables,
untrusted-data readers) and the naming rules — files, classes, and a verb vocabulary
for methods where find/require/read/list/apply/render/handle each state a contract.
Two properties fell out of the move, and they are why it was worth doing:
- The catalog can be driven with no window and no Electron at all. The smoke test
assembles the same services against the same ports in a plain Node process; it used
to be a script that reimplemented the bridge.
- The window never receives a filesystem path. A title crosses the bridge without
one, and launching is asked for by name, resolved in the main process from the
store's own state. Verified with a fake launcher: an unknown name answers false, a
native title resolves to its menu entry, a hosted one to its catalog URL.
Types are mandatory, including where inference would manage: explicit return,
parameter and property types, strict plus noUncheckedIndexedAccess,
exactOptionalPropertyTypes, noImplicitOverride and noPropertyAccessFromIndexSignature,
typescript-eslint strictTypeChecked and stylisticTypeChecked, exhaustive switches, no
any, no non-null assertions, and no casts on foreign data — engine stdout and the
registry go through readers that turn unknown into typed values. naming-convention
enforces the patterns rather than trusting them.
Two rule conflicts had to be decided rather than papered over. typedef and
no-inferrable-types disagree about `fallback: string = ''`: the annotation wins, since a
signature states its types. erasableSyntaxOnly is off, because it forbids constructor
parameter properties, which are how dependencies are declared here.
The preload and the renderer are bundled by esbuild into one file each: a sandboxed
preload may not require its own modules, and a module script over file:// is blocked by
the page's own origin rules. tsc compiles the rest. The package ships build/** and
package.json — 111 entries, no sources, no toolchain.
New targets: build, typecheck, lint, lint-fix, and check — typecheck, lint, then both
test suites, cheapest failure first. Every script that runs the app builds first, so a
stale bundle cannot be tested.
Nothing about the window changed: same side menu, same categories, same switcher, same
two languages. make check is clean, both test suites pass with one store and with two,
the packaged 1.3.0 bundle drives the real store, and the window was photographed before
and after — the two are the same picture.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,209 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { GameDtoMapper } from '../application/mappers/GameDtoMapper'
|
||||
import type { CatalogListing } from '../domain/models/CatalogListing'
|
||||
import type { InstalledStore } from '../domain/models/InstalledStore'
|
||||
import type { RegistryStore } from '../domain/models/RegistryStore'
|
||||
import { DESKTOP_STORE_ENGINE } from '../domain/models/StoreEngine'
|
||||
import { deriveStoreId } from '../domain/models/StoreIdentity'
|
||||
import { HttpTextClient } from '../infrastructure/http/HttpTextClient'
|
||||
import { PythonEngineProcessRunner } from '../infrastructure/process/PythonEngineProcessRunner'
|
||||
import { SystemPythonRuntimeLocator } from '../infrastructure/process/SystemPythonRuntimeLocator'
|
||||
import { FileSystemInstalledStoreRepository } from '../infrastructure/repositories/FileSystemInstalledStoreRepository'
|
||||
import { HttpStoreRegistryRepository } from '../infrastructure/repositories/HttpStoreRegistryRepository'
|
||||
import { PythonStoreCatalogGateway } from '../infrastructure/repositories/PythonStoreCatalogGateway'
|
||||
import type { GameDto } from '../shared/contracts/dto/GameDto'
|
||||
import { ENGLISH_MESSAGES } from '../shared/i18n/EnglishMessages'
|
||||
import { HUNGARIAN_MESSAGES } from '../shared/i18n/HungarianMessages'
|
||||
import { LOCALES } from '../shared/i18n/MessageBundle'
|
||||
|
||||
/**
|
||||
* Drives the store with no window and no Electron at all.
|
||||
*
|
||||
* This is the second composition root, and the reason the layers are worth having:
|
||||
* the same services the window uses are assembled here against the same ports, so an
|
||||
* integration mistake shows up in a terminal rather than in a screenshot.
|
||||
*
|
||||
* npm run smoke the store on this machine
|
||||
* SMOKE_HOME=/path/to/store-home npm run smoke a sandbox store
|
||||
*/
|
||||
class SmokeTest {
|
||||
private failed = false
|
||||
|
||||
private readonly stores = new FileSystemInstalledStoreRepository()
|
||||
private readonly pythonLocator = new SystemPythonRuntimeLocator()
|
||||
private readonly catalogGateway = new PythonStoreCatalogGateway(
|
||||
new PythonEngineProcessRunner(this.pythonLocator)
|
||||
)
|
||||
private readonly httpClient = new HttpTextClient()
|
||||
private readonly registry = new HttpStoreRegistryRepository(this.httpClient)
|
||||
private readonly gameMapper = new GameDtoMapper()
|
||||
|
||||
public async run (): Promise<number> {
|
||||
console.log('warp-engine-desktop-gui smoke test')
|
||||
|
||||
if (!this.checkPython()) return 1
|
||||
this.checkMessages()
|
||||
await this.checkRegistry()
|
||||
|
||||
const store = this.findStore()
|
||||
if (store === null) return this.failed ? 1 : 0
|
||||
await this.checkCatalog(store)
|
||||
|
||||
return this.failed ? 1 : 0
|
||||
}
|
||||
|
||||
private checkPython (): boolean {
|
||||
const runtime = this.pythonLocator.findRuntime()
|
||||
if (runtime === null) {
|
||||
this.reportBad('python', 'not found — the store cannot run')
|
||||
return false
|
||||
}
|
||||
this.reportOk('python', runtime.version)
|
||||
return true
|
||||
}
|
||||
|
||||
/** The bundles are typed against one key set, so this only counts them. */
|
||||
private checkMessages (): void {
|
||||
const english = Object.keys(ENGLISH_MESSAGES).length
|
||||
const hungarian = Object.keys(HUNGARIAN_MESSAGES).length
|
||||
if (english === hungarian) this.reportOk('strings', `${String(english)} keys × ${String(LOCALES.length)} languages`)
|
||||
else this.reportBad('strings', `en has ${String(english)}, hu has ${String(hungarian)}`)
|
||||
}
|
||||
|
||||
private async checkRegistry (): Promise<void> {
|
||||
try {
|
||||
const stores = await this.registry.listStores()
|
||||
if (stores.length === 0) {
|
||||
this.reportBad('registry', `${this.registry.sourceUrl} returned no stores`)
|
||||
return
|
||||
}
|
||||
this.reportOk('registry', `${String(stores.length)} store(s) from ${this.registry.sourceUrl}`)
|
||||
for (const store of stores) {
|
||||
this.reportOk(` ${store.name}`, `${store.catalogUrl} · ${deriveStoreId(store)}`)
|
||||
await this.checkStoreConfig(store)
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
this.reportBad('registry', `${this.registry.sourceUrl}: ${this.describe(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A store repository without a config.json still installs — the engine merges what
|
||||
* it is given onto its defaults — so an absent file is reported, not failed.
|
||||
*/
|
||||
private async checkStoreConfig (store: RegistryStore): Promise<void> {
|
||||
const url = `${store.storeRepositoryUrl.replace(/\/+$/, '')}/raw/branch/master/config.json`
|
||||
try {
|
||||
const config: unknown = JSON.parse(await this.httpClient.readText(url))
|
||||
const sections = typeof config === 'object' && config !== null ? Object.keys(config).length : 0
|
||||
this.reportOk(' config.json', `${String(sections)} sections`)
|
||||
} catch (error: unknown) {
|
||||
this.reportOk(' config.json', `absent (${this.describe(error)}) — defaults would be used`)
|
||||
}
|
||||
}
|
||||
|
||||
private findStore (): InstalledStore | null {
|
||||
const sandbox = process.env['SMOKE_HOME']
|
||||
if (sandbox !== undefined && sandbox.length > 0) {
|
||||
const home = path.resolve(sandbox)
|
||||
const store: InstalledStore = {
|
||||
id: path.basename(home).replace(DESKTOP_STORE_ENGINE.homeSuffix, ''),
|
||||
name: path.basename(home),
|
||||
home,
|
||||
scriptPath: path.join(home, DESKTOP_STORE_ENGINE.scriptFileName),
|
||||
configPath: path.join(home, 'config.json'),
|
||||
engine: DESKTOP_STORE_ENGINE.id
|
||||
}
|
||||
for (const file of [store.scriptPath, store.configPath]) {
|
||||
if (!fs.existsSync(file)) {
|
||||
this.reportBad('SMOKE_HOME', `${file} is missing`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
this.reportOk('store (SMOKE_HOME)', store.home)
|
||||
return store
|
||||
}
|
||||
|
||||
const found = this.stores.findAll()[0]
|
||||
if (found === undefined) {
|
||||
console.log(' skip no store installed — run the app once, or set SMOKE_HOME')
|
||||
console.log(` it would be installed in ${this.stores.resolveDefaultHome('ttg')}`)
|
||||
return null
|
||||
}
|
||||
this.reportOk('store found', `${found.id} in ${found.home}`)
|
||||
return found
|
||||
}
|
||||
|
||||
private async checkCatalog (store: InstalledStore): Promise<void> {
|
||||
const logLines: string[] = []
|
||||
const progress = { onLog: (line: string): void => { logLines.push(line) } }
|
||||
|
||||
const engine = this.catalogGateway.readEngineVersion(store)
|
||||
if (engine === null) this.reportBad('engine', 'the store did not answer --version')
|
||||
else if (!engine.supported) this.reportBad('engine', `${engine.text} is too old for this client`)
|
||||
else this.reportOk('engine', engine.text)
|
||||
|
||||
const paths = await this.catalogGateway.readPaths(store, progress)
|
||||
if (paths.operatingSystem.length > 0 && paths.storeFolder.length > 0) {
|
||||
this.reportOk('paths', `${paths.operatingSystem} → ${paths.storeFolder}`)
|
||||
} else {
|
||||
this.reportBad('paths', JSON.stringify(paths))
|
||||
}
|
||||
|
||||
const listing: CatalogListing = await this.catalogGateway.listGames(store, progress)
|
||||
if (listing.games.length === 0) {
|
||||
this.reportBad('list', 'no games came back')
|
||||
return
|
||||
}
|
||||
const games = this.gameMapper.toDtoList(listing.games, listing.paths?.catalogBaseUrl ?? '')
|
||||
this.reportListing(games)
|
||||
|
||||
if (logLines.length > 0) this.reportOk('stderr log', `${String(logLines.length)} lines (kept off stdout)`)
|
||||
}
|
||||
|
||||
private reportListing (games: readonly GameDto[]): void {
|
||||
const native = games.filter((game: GameDto): boolean => game.mode === 'app').length
|
||||
const hosted = games.length - native
|
||||
this.reportOk('list', `${String(games.length)} titles (app:${String(native)}, web:${String(hosted)})`)
|
||||
|
||||
const withoutTitle = games.filter((game: GameDto): boolean =>
|
||||
game.name.length === 0 || game.title.length === 0 || game.platform.length === 0)
|
||||
if (withoutTitle.length > 0) this.reportBad('game shape', `${String(withoutTitle.length)} entries are incomplete`)
|
||||
else this.reportOk('game shape', 'name, title, platform, version, mode, installed, updateAvailable')
|
||||
|
||||
const installed = games.filter((game: GameDto): boolean => game.installed)
|
||||
this.reportOk('installed', `${String(installed.length)} of ${String(games.length)}`)
|
||||
|
||||
const unlaunchable = installed.filter((game: GameDto): boolean => !game.launchable)
|
||||
if (unlaunchable.length > 0) this.reportBad('launch targets', `${String(unlaunchable.length)} installed titles have nothing to launch`)
|
||||
else if (installed.length > 0) this.reportOk('launch targets', 'every installed title has one')
|
||||
|
||||
const withArt = games.filter((game: GameDto): boolean => game.imageUrl !== null)
|
||||
if (withArt.length > 0) {
|
||||
const first = withArt[0]
|
||||
if (first !== undefined) this.reportOk('box art', first.imageUrl ?? '')
|
||||
}
|
||||
}
|
||||
|
||||
private describe (error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
private reportOk (label: string, value?: string): void {
|
||||
console.log(` ok ${label}${value === undefined ? '' : `: ${value}`}`)
|
||||
}
|
||||
|
||||
private reportBad (label: string, value: string): void {
|
||||
this.failed = true
|
||||
console.log(` FAIL ${label}: ${value}`)
|
||||
}
|
||||
}
|
||||
|
||||
void new SmokeTest().run().then(
|
||||
(code: number): void => { process.exitCode = code },
|
||||
(error: unknown): void => {
|
||||
console.log(` FAIL error: ${error instanceof Error ? error.message : String(error)}`)
|
||||
process.exitCode = 1
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user