chore(8.0): collapse dead defensive guards + redundant polyfills

Follow-up to the browser/cloud/threading sweep — everything that was guarding
against unreachable runtimes is now dead.

cacheManager.ts: Environment enum + this.environment field removed (only NODE
was reachable). StorageType narrowed to MEMORY + FILESYSTEM. navigator.deviceMemory
and performance.memory paths in detectOptimalCacheSize + detectAvailableMemory
deleted; node:os is the sole source. environmentConfig keeps the index signature
for future per-runtime tuning but only the node slot is wired.

Dead 'typeof window === undefined' guards (the check is always true on 8.0):
paramValidation, structuredLogger, mutex, brainy.ts stats block, and
networkTransport ws-dynamic-import all collapsed. IntegrationLoader's inverse
guard ('!== undefined' returning 'browser') deleted. mutex's createMutex default
type simplified from "(typeof window === 'undefined' ? 'file' : 'memory')" to
plain 'file'.

Redundant TextEncoder/TextDecoder polyfills: Node 22+ ships both as globals.
src/utils/textEncoding.ts deleted (applyTensorFlowPatch was named for a defunct
dep and only re-assigned globals already present). setup.ts collapsed to an
empty stable import target. unified.ts loses its applyTensorFlowPatch re-export.

modelAutoConfig.getModelPath() loses the unreachable trailing fallback now
that isNode() is effectively the only branch the function ever takes.

jsonProcessing.ts left unchanged — its 'typeof document' checks are value-shape
guards on the parsed JSON, not environment detection.
This commit is contained in:
David Snelling 2026-06-09 16:46:16 -07:00
parent 266715aeee
commit 42159f2bd7
11 changed files with 121 additions and 397 deletions

View file

@ -105,16 +105,14 @@ export class FileMutex implements MutexInterface {
private async loadNodeModules(): Promise<void> {
if (this.modulesLoaded) return
if (typeof window === 'undefined') {
// Modern ESM-compatible dynamic imports
const [fs, path] = await Promise.all([
import('fs'),
import('path')
])
this.fs = fs
this.path = path
this.modulesLoaded = true
}
// Modern ESM-compatible dynamic imports
const [fs, path] = await Promise.all([
import('fs'),
import('path')
])
this.fs = fs
this.path = path
this.modulesLoaded = true
}
async acquire(key: string, timeout: number = 30000): Promise<() => void> {
@ -255,9 +253,9 @@ export function createMutex(options?: {
type?: 'memory' | 'file'
lockDir?: string
}): MutexInterface {
const type = options?.type || (typeof window === 'undefined' ? 'file' : 'memory')
const type = options?.type || 'file'
if (type === 'file' && typeof window === 'undefined') {
if (type === 'file') {
const lockDir = options?.lockDir || '.brainy/locks'
return new FileMutex(lockDir)
}

View file

@ -13,21 +13,17 @@ import { findCallerLocation } from './callerLocation.js'
// Dynamic import for Node.js os and fs modules
let os: any = null
let fs: any = null
if (typeof window === 'undefined') {
try {
os = await import('node:os')
fs = await import('node:fs')
} catch (e) {
// OS/FS modules not available
}
try {
os = await import('node:os')
fs = await import('node:fs')
} catch (e) {
// OS/FS modules not available
}
// Browser-safe memory detection
const getSystemMemory = (): number => {
if (os) {
return os.totalmem()
}
// Browser fallback: assume 4GB
return 4 * 1024 * 1024 * 1024
}
@ -35,7 +31,6 @@ const getAvailableMemory = (): number => {
if (os) {
return os.freemem()
}
// Browser fallback: assume 2GB available
return 2 * 1024 * 1024 * 1024
}

View file

@ -311,16 +311,11 @@ export class StructuredLogger {
}
if (this.config.includeHost) {
// Use dynamic import for hostname (Node.js only)
if (typeof window === 'undefined') {
try {
const os = require('node:os')
entry.host = os.hostname()
} catch {
entry.host = 'unknown'
}
} else {
entry.host = window.location?.hostname || 'browser'
try {
const os = require('node:os')
entry.host = os.hostname()
} catch {
entry.host = 'unknown'
}
}

View file

@ -1,69 +0,0 @@
import { isNode } from './environment.js'
// Simplified TextEncoder/TextDecoder utilities for Node.js compatibility
// No longer needs complex TensorFlow.js patches - only basic TextEncoder/TextDecoder
/**
* Flag to track if the patch has been applied
*/
let patchApplied = false
/**
* Apply TextEncoder/TextDecoder patches for Node.js compatibility
* Simplified version for Transformers.js/ONNX Runtime
*/
export async function applyTensorFlowPatch(): Promise<void> {
if (patchApplied || !isNode()) return
try {
console.log('Brainy: Applying TextEncoder/TextDecoder patch for Node.js')
// Get the appropriate global object
const globalObj = (() => {
if (typeof globalThis !== 'undefined') return globalThis
if (typeof global !== 'undefined') return global
throw new Error(
'Cannot apply TextEncoder/TextDecoder patches: No global object found. ' +
'This environment does not have globalThis or global defined.'
)
})()
// Make sure TextEncoder and TextDecoder are available globally
if (!globalObj.TextEncoder) {
globalObj.TextEncoder = TextEncoder
}
if (!globalObj.TextDecoder) {
globalObj.TextDecoder = TextDecoder
}
// Also set them on the global object for older code
if (typeof global !== 'undefined') {
if (!global.TextEncoder) {
global.TextEncoder = TextEncoder
}
if (!global.TextDecoder) {
global.TextDecoder = TextDecoder
}
}
patchApplied = true
console.log('Brainy: TextEncoder/TextDecoder patches applied successfully')
} catch (error) {
console.warn('Brainy: Failed to apply TextEncoder/TextDecoder patch:', error)
}
}
export function getTextEncoder(): TextEncoder {
return new TextEncoder()
}
export function getTextDecoder(): TextDecoder {
return new TextDecoder()
}
// Apply patch immediately if in Node.js
if (isNode()) {
applyTensorFlowPatch().catch((error) => {
console.warn('Failed to apply TextEncoder/TextDecoder patch at module load:', error)
})
}