bsg-nexus
v1.0.0
Published
Enterprise TypeScript Node.js framework with React, React Native, XML UI, security, performance, app build, and Java/Android tooling.
Maintainers
Readme
BSG-Nexus
TypeScript-first Node.js framework with production middleware, React/React Native clients, Android-style XML UI, universal app tooling, dependency injection, Java/JDK/SDK/NDK planning, background tasks, and build planning for web, PWA, desktop, Android, iOS, and Java.
Author: Pradeep Kumar Sheoran
Developer: Pradeep Kumar Sheoran (Looking For Job Change)
Company: BSG Technologies
Contact / WhatsApp: +91-8595147850
Official Website: https://bsgtechnologies.com
Visit here to meet, learn, contribute, and discuss new topics with us: BSG Technologies
License: MIT
Why BSG-Nexus
BSG-Nexus is designed as a professional, enterprise-friendly full-stack foundation. It combines backend APIs, middleware, security, performance, React/React Native tooling, XML UI, app build planning, Java/Android support, CLI generators, and documentation-first developer experience in one package.
Install
npm install bsg-nexusstormfetch is included as a runtime dependency and powers the React/React Native client helpers.
Quick Start
Create a production-ready API in a few lines:
import { createServer, cors, helmet, logger } from 'bsg-nexus';
const app = createServer();
app.use(helmet());
app.use(cors());
app.use(logger());
app.get('/', () => ({ message: 'Hello from BSG-Nexus' }));
app.listen(3000, () => {
console.log('BSG-Nexus listening on http://localhost:3000');
});Create a React/React Native client:
import { createNexusClient } from 'bsg-nexus/react';
export const api = createNexusClient({
baseURL: 'https://api.example.com',
platform: 'web',
retry: 2,
cache: true
});Create an Android-style XML UI layout:
<LinearLayout responsive="true" mobileOrientation="vertical" desktopOrientation="horizontal">
<Card>
<TextView text="{{title}}" visibleWhen="user.role == 'admin'" />
<PasswordInput placeholder="Password" />
<Button text="Login" onClick="AuthService.login" runOn="background" />
</Card>
</LinearLayout>What BSG-Nexus Gives You
- Fast Node.js API framework with typed routes, middleware, validation, plugins, and testing helpers.
- Production middleware: request IDs, secure headers, CORS, rate limits, structured logging, error formatting, gzip/brotli compression.
- React and React Native client layer with typed API clients, React Query-style helpers, React 19 Actions, auth, uploads, realtime, offline sync, notifications, and deep links.
- Android-style XML UI for React and React Native: design screens in XML, bind values, call services, use permissions, responsive rules, lifecycle, and hardware acceleration hints.
- Universal app layer: app/website compatibility targets, responsive layouts, dependency injection, constructor/lifecycle classes, multi-thread task abstraction, and build plans for web/APK/iOS cloud.
- Studio and enterprise layer: XML live preview HTML, XML Form engine, XML DataTable engine, route-to-client generator, RBAC, request signing, audit logs, tracing, memory repository, testing DSL, and deploy presets.
- Security and performance pack: API keys, HMAC replay protection, CSRF, brute-force protection, sanitization, secure sessions, refresh rotation, response cache, request dedupe, route timings, static asset headers, worker tasks, and cluster planning.
- OOP/MVC and app runtime pack: base controllers/services/repositories, MVC modules, Gradle-style variants/flavors, assets/vector/logo helpers, app lifecycle, crash reporter, app bridge, console, run/debug plans, and Android Studio plan helpers.
- Java and Android toolchain pack: Java source generator, JDK plan, Android SDK plan, Android NDK plan, compiler plan, interpreter plan, and Gradle Java/Android build guidance.
- CLI generators for projects, clients, XML layouts, manifests, and build plans.
Enterprise Feature Map
| Area | What users get |
| --- | --- |
| Backend API | HTTP server, router, middleware, validation, plugins, testing injection, docs endpoints. |
| Security | Helmet headers, API keys, HMAC signatures, CSRF, brute-force protection, session signing, refresh rotation, input sanitization, XML security, secret scanning. |
| Performance | Compression, response cache, request dedupe, route timing, static asset headers, worker task runner, cluster planning, bundle report, image optimization. |
| React Web | StormFetch client, query helpers, mutations, React Actions, uploads, auth kit, SSE/WebSocket, PWA helpers. |
| React Native | Native platform headers, offline sync, deep links, push notifications, auth storage, Android/iOS build plans. |
| XML UI | Android-style XML layouts, forms, data tables, theme tokens, platform files, responsive props, precompile cache, profiler, secure validation. |
| App Runtime | DI container, scopes, constructor screens, lifecycle hooks, thread pool, bridge, console, crash reporter, run/debug plans. |
| Multiplatform Build | Web, PWA, Electron, Tauri, Android APK, iOS cloud/local guidance, Gradle variants/flavors. |
| Java/Android | Java source generation, Activity/Service/Bridge templates, JDK/SDK/NDK setup plans, javac, jshell, Gradle commands. |
| Developer Tools | CLI generators, Nexus Studio, route-to-client generator, docs, deployment presets. |
New Advanced Features Added Recently
- Advanced XML UI components:
Card,Dialog,Drawer,Tabs,BottomSheet,FAB,Badge,Avatar,Toast,Snackbar,VirtualList,Skeleton,PasswordInput,SearchInput,DatePicker,TimePicker,FilePicker,ColorPicker,Select,OTPInput,SafeArea,KeyboardAvoidingView. - Multiplatform XML helpers for web, native, Expo, PWA, Electron, and Tauri.
- Nexus Studio upgraded with component palette, viewport simulator, validation panel, copy, and XML export.
- PWA manifest and service worker strategy helpers.
- Electron and Tauri desktop build planning.
- Java/JDK/Android SDK/Android NDK/compiler/interpreter planning.
- Secure XML validation, secret scanning, dependency audit summary.
- XML precompile cache, XML complexity score, XML profiler, image optimization, bundle report.
Production Setup
import {
compression,
helmet,
installErrorHandler,
logger,
rateLimit,
requestId
} from 'bsg-nexus';
app.use(requestId());
app.use(helmet({ hsts: true, contentSecurityPolicy: "default-src 'self'" }));
app.use(rateLimit({ max: 100, windowMs: 60_000 }));
app.use(compression({ thresholdBytes: 1024 }));
app.use(logger(console, { slowRequestMs: 250, includeHeaders: true }));
installErrorHandler(app, { environment: 'production' });Function Guide
Core Server
| Function | Use |
| --- | --- |
| createServer(options?) | Creates a BSG-Nexus HTTP app. Use it to register middleware, routes, plugins, and start the server. |
| app.use(middleware) | Adds global middleware for every request. Use for security, logging, request IDs, compression, auth, etc. |
| app.get/post/put/patch/delete(path, options?, handler) | Registers HTTP routes. Use ctx.params, ctx.query, and ctx.body inside handlers. |
| app.plugin(plugin, options?) | Installs reusable framework features such as auth, metrics, docs, notifications. |
| app.inject(request) | Tests routes without opening a port. Great for fast unit/integration tests. |
| app.listen(port) | Starts the Node.js HTTP server. |
Middleware
| Function | Use |
| --- | --- |
| requestId(options?) | Adds a traceable x-request-id to request state and response headers. |
| logger(log?, options?) | Structured request logs with duration, status, IP, user-agent, redaction, and slow request warnings. |
| installErrorHandler(app, options?) | Central error response format. Hides stack traces in production and includes requestId. |
| helmet(options?) | Security headers: CSP, HSTS, frame options, referrer policy, permissions policy, HTTPS redirect. |
| cors(options?) | Cross-origin access rules for web apps. |
| rateLimit(options?) | IP/user based request limiting with standard and legacy headers. |
| compression(options?) | Gzip/brotli compression with thresholds and content-type filtering. |
| json(options?) | Body parsing compatibility middleware; core body parsing supports JSON/text/urlencoded/raw. |
Validation
| Function | Use |
| --- | --- |
| SchemaBuilder | Chainable validation for request bodies. |
| fromZod(schema) | Adapts Zod-style schemas through safeParse. |
| classValidator(Class) | Creates class-shaped payloads for DTO-style validation flows. |
Plugins
| Function | Use |
| --- | --- |
| AuthPlugin | Adds lightweight signed token helpers and auth middleware. |
| MetricsPlugin | Adds /health, /ready, /live, /metrics endpoints. |
| SwaggerPlugin | Adds /docs and /docs-json OpenAPI-style endpoint docs. |
| WebSocketPlugin | Registers WebSocket metadata for realtime integrations. |
| NotificationsPlugin | Adds notification token registration and send endpoints backed by your provider. |
| definePlugin(plugin) | Creates custom plugins with a typed install contract. |
React And React Native Clients
| Function | Use |
| --- | --- |
| createNexusClient(options) | Creates a StormFetch-powered API client with platform headers, retry, cache, request IDs, and auth hooks. |
| createTypedNexusClient<T>() | Creates a typed endpoint client for strict API calls. |
| createNexusQueryOptions(client, path, config?) | Creates React Query-compatible queryKey and queryFn. |
| createNexusMutation(client, path, method?) | Creates mutation functions for POST/PUT/PATCH/DELETE. |
| createNexusAction(client, path) | React 19 form Action helper returning { ok, data, error }. |
| createNexusAuthKit(options) | Login/session/refresh/logout helper for web or mobile token storage. |
| createMemoryTokenStorage() | Simple in-memory token store for demos/tests. Replace with SecureStore/Keychain/localStorage in apps. |
| createUploadKit(client) | Uploads files/form data with progress callbacks. |
| createWebSocketSubscription() | Realtime WebSocket subscription with optional reconnect. |
| createSseSubscription() | Server-Sent Events subscription for web/server streaming. |
| createOfflineSyncQueue(options) | Offline-first mobile/web queue with retry/flush behavior. |
| createDeepLink(path, query?, scheme?) | Builds app deep links. |
| parseDeepLink(url) | Parses incoming deep links into path and query. |
| createPushNotificationClient(client) | Registers push tokens and sends notifications through your API. |
Nexus XML UI
| Function | Use |
| --- | --- |
| parseNexusXmlLayout(xml) | Parses Android-style XML into a layout tree. |
| createNexusXmlRenderer(adapter) | Renders XML layout trees through React or React Native adapters. |
| renderNexusXmlNode(node, adapter, context?) | Renders an already parsed XML node. |
| bindNexusXmlLayout(node, values) | Replaces {{value}} and {{user.name}} bindings. |
| validateNexusXmlLayout(node) | Finds invalid XML UI components or missing required props. |
| configureNexusXmlCache({ maxSize }) | Controls parser cache size for repeated XML layouts. |
| evaluateNexusXmlCondition(expression, values) | Evaluates visibleWhen and disabledWhen expressions with && and ||. |
| createNexusServiceRegistry(services?) | Registers OOP-style services callable from XML, such as AuthService.login. |
| defineNexusService(service) | Defines a service object with name, scope/background, and methods. |
| parseNexusManifest(xml) | Parses nexus.manifest.xml for permissions, services, screens, and deep links. |
| ensureNexusPermissions(declarations, runtime) | Checks/requests manifest permissions through your platform adapter. |
| createMemoryPermissionRuntime() | Demo/test permission runtime. Replace with browser/RN permissions in apps. |
| createNexusNavigationMap(manifest) | Converts manifest screens into a route map. |
| createNexusDeepLinkMap(manifest) | Converts manifest deep links into scheme/path mapping. |
| createNexusFormDefinition(node) | Extracts XML <Form> fields and submit target from a layout tree. |
| validateNexusForm(form, values) | Validates XML form values using required, requiredWhen, pattern, minLength, and maxLength. |
| createNexusDataTableQuery(input?) | Normalizes table query state: values, filters, page, pageSize, and sort. |
| resolveNexusDataTable(rows, query?) | Sorts and paginates in-memory rows with the same contract server-side tables can use. |
| createNexusTheme(tokens?) | Creates design tokens for colors, spacing, typography, and light/dark mode. |
| parseNexusTheme(node) | Reads XML theme nodes such as Color, Spacing, and Typography. |
| applyNexusThemeTokens(props, theme) | Converts token names like primary or md into style values. |
| resolveNexusPlatformFile(base, platform, files) | Picks home.web.xml, home.native.xml, home.pwa.xml, or fallback home.xml. |
| createPlatformPropResolver(platform) | Converts platform props such as webClassName and nativeVariant. |
| precompileNexusXml(xml) | Parses and caches XML layouts for repeated renders. |
| getNexusXmlComplexity(node) | Scores layout depth and node count for performance checks. |
| profileNexusXml(node) | Lists every XML node with path and complexity. |
| findSlowNexusXmlNodes(entries, threshold?) | Finds complex nodes that may need virtualization or splitting. |
| validateSecureNexusXml(node) | Blocks unsafe XML tags, inline JavaScript, and unsafe URLs. |
| sanitizeNexusXmlText(value) | Sanitizes XML-bound values before rendering. |
Example XML:
<LinearLayout responsive="true" mobileOrientation="vertical" desktopOrientation="horizontal">
<TextView text="{{title}}" visibleWhen="user.role == 'admin'" />
<EditText bind="user.name" value="{{user.name}}" />
<Button text="Login" onClick="AuthService.login" runOn="background" hardwareAccelerated="true" animate="fadeIn" />
</LinearLayout>Universal App Layer
| Function | Use |
| --- | --- |
| detectNexusCompatibilityTarget(platform?) | Detects web/native runtime capabilities such as DOM, workers, and native modules. |
| createUniversalNexusTarget(target?) | Creates an explicit compatibility target for app/website rendering. |
| getNexusBreakpoint(viewport) | Returns mobile, tablet, or desktop. |
| applyNexusResponsiveLayout(node, viewport) | Applies XML responsive props like hideOn, showOn, mobileOrientation, columns, and safeArea. |
| createNexusContainer(providers?) | Dependency injection container. |
| container.register(token, provider) | Registers class/value/factory dependencies. |
| container.resolve(token, scopeId?) | Resolves dependencies using singleton/screen/request/transient scopes. |
| container.createScope(scopeId) | Creates a screen/request scope with automatic disposal. |
| createNexusScreen(Class, deps?, props?) | Constructor/lifecycle helper for screen classes. |
| runNexusLifecycle(instance, phase, values?) | Runs onMount, onUpdate, or onDestroy. |
| createNexusThreadPool(adapter?) | Multi-thread abstraction for main/worker/background tasks. |
| createInlineThreadAdapter() | Default task adapter that runs handlers inline. |
| createNexusBuildPlan(target, options?) | Returns commands/notes for web, PWA, Electron, Tauri, Android APK, and iOS/cloud builds. |
| renderNexusBuildPlan(plan) | Converts a build plan into CLI-readable text. |
| createNexusPwaManifest(input) | Generates a browser install manifest for PWA apps. |
| createNexusServiceWorkerPlan(strategy?) | Plans service worker files and cache strategy. |
| createDesktopBuildPlan(target) | Creates Electron or Tauri desktop packaging guidance. |
| createNexusJavaSource(options) | Generates Java class, interface, Activity, Service, bridge, or module source code. |
| createNexusJavaEnvironmentPlan(options?) | Lists JDK, Android SDK, Android NDK, compiler, interpreter, and Gradle environment checks. |
| createNexusJavaCompilePlan(options?) | Creates javac, jshell, or Gradle Android build commands. |
| createNexusAndroidSdkPlan(apiLevel?) | Lists Android SDK packages and sdkmanager commands. |
| createNexusAndroidNdkPlan(version?) | Lists Android NDK/CMake packages and verification commands. |
Studio, Security, Testing, Database, Observability
| Function | Use |
| --- | --- |
| createNexusStudioHtml(options?) | Generates a browser-based XML Studio with component palette, viewport preview, manifest editor, validation, copy, and XML export. |
| generateNexusClientFromRoutes(routes) | Generates React/RN client service functions from server route records. |
| requireAuth() | Middleware that blocks unauthenticated requests. |
| requireRbac({ roles, permissions }) | Middleware for role/permission protected routes. |
| canAccess(user, policy) | Checks RBAC access in services or UI logic. |
| signNexusRequest(payload, secret) | Creates HMAC signatures for secure request signing. |
| verifyNexusRequestSignature(payload, signature, secret) | Verifies signed requests. |
| createMemoryAuditSink() | Stores audit events in memory for tests/dev. |
| createAuditEvent(input) | Creates a timestamped audit log event. |
| createMemoryRepository(seed?) | In-memory repository implementing CRUD for demos/tests. |
| tracing(tracer?) | Middleware that creates request spans. |
| createMemoryTracer() | In-memory tracer for tests/dev observability. |
| nexusTest(app) | Fluent API test helper: await nexusTest(app).get('/').expect(200). |
| createNexusDeployPreset(target) | Generates deployment files/commands for Docker, Vercel, AWS, or Fly. |
Security And Performance
| Function | Use |
| --- | --- |
| createApiKey() | Generates an API key and hashed storage value. |
| apiKeyAuth(store, options?) | Middleware for scoped, expiring, revocable API keys. |
| hmacSignature(options) | Middleware for signed requests with timestamp and replay protection. |
| csrfProtection(options?) | Double-submit CSRF protection with cookie/header validation. |
| bruteForceProtection(options?) | Tracks failed attempts and applies cooldown windows. |
| sanitizeInput(options?) | Removes script URLs/tags and rejects prototype pollution keys. |
| RefreshTokenRotationStore | Token family rotation and reuse detection helper. |
| signSession(payload, options) | Creates signed session payloads with timeout metadata. |
| verifySession(token, options) | Verifies signed sessions and idle/absolute expiry. |
| responseCache(options?) | Route response cache with TTL and cache headers. |
| requestDedupe(options?) | Marks duplicate in-flight request keys. |
| routeTiming() | Captures route count, average, max, and total timing stats. |
| createStaticAssetHeaders(content) | Creates ETag and cache-control headers for static assets. |
| runWorkerTask(task) | Runs CPU-heavy JavaScript in a Node worker thread. |
| createClusterPlan(options?) | Produces multi-core deployment guidance and cluster settings. |
| createImageOptimizationPlan(src, options?) | Creates responsive image widths, lazy loading, and placeholder strategy. |
| createSrcSet(plan) | Converts an image optimization plan into an HTML srcset. |
| createBundleReport(files, threshold?) | Totals bundle size and warns on large assets. |
| scanForSecrets(files) | Scans source/config text for API keys, secrets, private keys, and AWS keys. |
| createDependencyAuditSummary(input) | Summarizes vulnerability, outdated dependency, and license risk counts. |
OOP, MVC, Gradle, Assets, App Runtime
| Function | Use |
| --- | --- |
| BaseController | Parent class with ok, created, notFound, and badRequest helpers. |
| BaseService | Parent service class for lifecycle-friendly service inheritance. |
| BaseRepository | Parent repository with in-memory CRUD behavior. |
| CrudController | Abstract CRUD controller wired to a repository contract. |
| createMvcModule(options) | Registers MVC controllers/services/imports as a module. |
| registerMvcController(app, definition) | Binds class controller methods to routes. |
| WithPagination, WithValidation, WithAudit | Mixins for common OOP behavior. |
| createNexusGradleConfig(config?) | Creates Gradle-style variants/flavors/signing config. |
| createNexusGradleBuildPlan(config, options) | Creates Android/iOS/web build commands with variant/flavor support. |
| createNexusAssetManifest(input?) | Describes app icons, splash, and vector assets. |
| createNexusVectorImage(options) | Generates SVG vector images. |
| createNexusAppLogo(options) | Generates a simple app logo SVG. |
| createNexusCrashReporter() | Captures crash reports like lightweight Crashlytics. |
| createNexusBridge() | Message bridge between app layers/native adapters. |
| createNexusConsole() | In-app console log collector. |
| createNexusRunPlan(target, options?) | Creates run/debug commands for web/android/iOS. |
| createAndroidStudioPlan(projectDir?) | Creates Android Studio open/sync guidance. |
CLI Commands
nexus init my-api --template=minimal
nexus init my-bff --template=react-bff
nexus init my-mobile --template=expo
nexus client --target=react
nexus client --target=react-native
nexus layout home
nexus manifest myapp
nexus app init myapp
nexus app build web
nexus app build android
nexus app build ios --cloud=true
nexus studio
nexus routes
nexus deploy docker
nexus mvc user
nexus gradle init
nexus gradle build android --variant=release --flavor=pro
nexus java class --class=Main --package=com.example.app
nexus java activity --class=MainActivity --package=com.example.app
nexus java env --jdk=21 --ndk=true
nexus java sdk --api=35
nexus java compile --file=src/main/java/com/example/Main.java --main=com.example.Main
nexus assets BSG-Nexus
nexus run android
nexus debug android
nexus android-studio androidImportant Build Notes
- Web builds can be generated with a React/Vite style project.
- Android APK builds require Android SDK/Gradle or Expo/EAS.
- iOS local builds require macOS and Xcode.
- Windows users can generate iOS config and trigger cloud builds, but cannot compile local IPA files without macOS/Xcode.
Documentation
- Core API:
docs/api/core.md - Full function reference:
docs/api/function-reference.md - Complete function catalog:
docs/api/complete-function-catalog.md - Feature list:
docs/guides/feature-list.md - Java/JDK/SDK/NDK:
docs/guides/java-jdk-sdk-ndk.md - Studio/forms/tables:
docs/guides/studio-forms-tables.md - OOP/MVC/Gradle/app runtime:
docs/guides/mvc-gradle-app.md - Feature list:
docs/guides/feature-list.md - Middleware:
docs/guides/middleware.md - React/React Native clients:
docs/guides/react-native.md - XML UI:
docs/guides/xml-ui.md - Universal app builds:
docs/guides/app-builds.md - UI/multiplatform/security/performance:
docs/guides/ui-multiplatform-security-performance.md - Security:
docs/guides/security.md - Security and performance:
docs/guides/security-performance.md - Deployment:
docs/guides/deployment.md
Verification
npm run type-check
npm run build
npm test
npm run bench
npm pack --dry-run