@noxfly/noxus 3.0.0-dev.4 → 3.0.0-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/child.js.map +1 -0
- package/dist/child.mjs.map +1 -0
- package/dist/main.js.map +1 -0
- package/dist/main.mjs.map +1 -0
- package/dist/preload.js.map +1 -0
- package/dist/preload.mjs.map +1 -0
- package/dist/renderer.js.map +1 -0
- package/dist/renderer.mjs.map +1 -0
- package/package.json +10 -9
- package/.editorconfig +0 -16
- package/.github/copilot-instructions.md +0 -128
- package/.vscode/settings.json +0 -3
- package/AGENTS.md +0 -5
- package/eslint.config.js +0 -109
- package/scripts/postbuild.js +0 -31
- package/src/DI/app-injector.ts +0 -173
- package/src/DI/injector-explorer.ts +0 -201
- package/src/DI/token.ts +0 -53
- package/src/decorators/controller.decorator.ts +0 -58
- package/src/decorators/guards.decorator.ts +0 -15
- package/src/decorators/injectable.decorator.ts +0 -81
- package/src/decorators/method.decorator.ts +0 -66
- package/src/decorators/middleware.decorator.ts +0 -15
- package/src/index.ts +0 -10
- package/src/internal/app.ts +0 -219
- package/src/internal/bootstrap.ts +0 -141
- package/src/internal/exceptions.ts +0 -57
- package/src/internal/preload-bridge.ts +0 -75
- package/src/internal/renderer-client.ts +0 -374
- package/src/internal/renderer-events.ts +0 -110
- package/src/internal/request.ts +0 -102
- package/src/internal/router.ts +0 -365
- package/src/internal/routes.ts +0 -142
- package/src/internal/socket.ts +0 -75
- package/src/main.ts +0 -26
- package/src/non-electron-process.ts +0 -22
- package/src/preload.ts +0 -10
- package/src/renderer.ts +0 -13
- package/src/utils/forward-ref.ts +0 -31
- package/src/utils/logger.ts +0 -430
- package/src/utils/radix-tree.ts +0 -243
- package/src/utils/types.ts +0 -21
- package/src/window/window-manager.ts +0 -302
- package/tsconfig.json +0 -29
- package/tsup.config.ts +0 -50
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
# Copilot Instructions
|
|
2
|
-
|
|
3
|
-
## Core Architecture
|
|
4
|
-
- bootstrapApplication in [src/internal/bootstrap.ts](src/internal/bootstrap.ts) waits for Electron app readiness, applies log level config, wires the controller registrar, flushes DI, resolves NoxApp, registers routes and eager-loads, then returns a configured instance.
|
|
5
|
-
- [src/internal/app.ts](src/internal/app.ts) wires ipcMain events, spawns paired request/socket MessageChannels per renderer, and delegates handling to Router and NoxSocket.
|
|
6
|
-
- Package exports are split between renderer and main targets in [package.json](package.json); import Electron main APIs from @noxfly/noxus/main, renderer helpers from @noxfly/noxus or @noxfly/noxus/renderer, and preload helpers from @noxfly/noxus/preload.
|
|
7
|
-
- Dependency injection centers on RootInjector in [src/DI/app-injector.ts](src/DI/app-injector.ts); @Injectable triggers auto-registration through [src/DI/injector-explorer.ts](src/DI/injector-explorer.ts) and supports singleton, scope, and transient lifetimes.
|
|
8
|
-
- resetRootInjector() in [src/DI/app-injector.ts](src/DI/app-injector.ts) clears all bindings, singletons, and scoped instances — use it in tests to get a clean DI state between test suites.
|
|
9
|
-
- There is no Module decorator — controllers and services are standalone, registered via @Injectable and @Controller decorators with explicit deps arrays.
|
|
10
|
-
|
|
11
|
-
## Request Lifecycle
|
|
12
|
-
- Request objects from [src/internal/request.ts](src/internal/request.ts) wrap Electron MessageEvents and spawn per-request DI scopes on Request.context. They expose params, body, and query (Record<string, string>).
|
|
13
|
-
- Router in [src/internal/router.ts](src/internal/router.ts) indexes routes in a radix tree, merges controller-level and method-level decorators, and enforces root middlewares, route middlewares, then guards before invoking controller actions.
|
|
14
|
-
- The radix tree in [src/utils/radix-tree.ts](src/utils/radix-tree.ts) prioritizes static segments over parameter segments during search, so `addNote/:id` won't be shadowed by `:id`.
|
|
15
|
-
- ResponseException subclasses in [src/internal/exceptions.ts](src/internal/exceptions.ts) propagate status codes; throwing one short-circuits the pipeline so Router returns a structured error payload.
|
|
16
|
-
- Batch requests use HTTP method BATCH and normalization logic in Router.handleBatch; payloads must satisfy IBatchRequestPayload to fan out atomic subrequests.
|
|
17
|
-
|
|
18
|
-
## Communication Channels
|
|
19
|
-
- ipcMain listens for gimme-my-port and posts two transferable ports back to the renderer: index 0 carries request/response traffic, index 1 is reserved for socket-style push messages.
|
|
20
|
-
- NoxSocket in [src/internal/socket.ts](src/internal/socket.ts) maps sender IDs to {request, socket} channels and emits renderer events exclusively through channels.socket.port1. emit() returns void.
|
|
21
|
-
- Renderer helpers in [src/internal/renderer-events.ts](src/internal/renderer-events.ts) expose RendererEventRegistry.tryDispatchFromMessageEvent to route push events; the preload script must start both ports and hand the second to this registry.
|
|
22
|
-
- Renderer-facing bootstrap lives in [src/internal/renderer-client.ts](src/internal/renderer-client.ts); NoxRendererClient requests ports, wires request/socket handlers, tracks pending promises with configurable timeout (default 10s), and surfaces RendererEventRegistry for push consumption.
|
|
23
|
-
- Preload scripts should call exposeNoxusBridge from [src/internal/preload-bridge.ts](src/internal/preload-bridge.ts) to publish window.noxus.requestPort; the helper sends 'gimme-my-port' and forwards both transferable ports with the configured init message.
|
|
24
|
-
- When adjusting preload or renderer glue, ensure window.postMessage('init-port', ...) forwards both ports so the socket channel stays alive alongside the request channel.
|
|
25
|
-
|
|
26
|
-
## Route Definitions
|
|
27
|
-
- defineRoutes in [src/internal/routes.ts](src/internal/routes.ts) is the single source of truth for routing. It validates for duplicate and overlapping prefixes and supports nested children with inherited guards/middlewares.
|
|
28
|
-
- Parent routes can omit the load function and serve only as shared prefix containers for children.
|
|
29
|
-
- flattenRoutes recursively merges parent guards and middlewares into each child before validation.
|
|
30
|
-
|
|
31
|
-
## Decorator Conventions
|
|
32
|
-
- Controller paths omit leading/trailing slashes; method decorators (Get, Post, etc.) auto-trim segments via [src/decorators/method.decorator.ts](src/decorators/method.decorator.ts).
|
|
33
|
-
- Guards registered through Authorize in [src/decorators/guards.decorator.ts](src/decorators/guards.decorator.ts) aggregate at controller and action scope; they must resolve truthy or Router throws UnauthorizedException.
|
|
34
|
-
- Injectable lifetimes default to scope; use singleton for app-wide utilities (window managers, sockets) and transient for short-lived resources.
|
|
35
|
-
|
|
36
|
-
## Dependency Injection Internals
|
|
37
|
-
- InjectorExplorer in [src/DI/injector-explorer.ts](src/DI/injector-explorer.ts) accumulates registrations at import time and flushes in two phases (bind then resolve).
|
|
38
|
-
- To avoid a circular dependency between InjectorExplorer and Router, controller registration is decoupled via a ControllerRegistrar callback set by bootstrapApplication through setControllerRegistrar(). There is no require() call.
|
|
39
|
-
- flushAccumulated is serialized through a Promise-based lock (loadingLock) to prevent concurrent lazy module loads from corrupting the queue. Use waitForFlush() to await completion.
|
|
40
|
-
- Phase 2 validates that declared deps have a corresponding binding or singleton, and emits warnings for missing ones at startup.
|
|
41
|
-
|
|
42
|
-
## Logging and Utilities
|
|
43
|
-
- Logger in [src/utils/logger.ts](src/utils/logger.ts) standardizes color-coded log, warn, error, and comment output; it supports configurable log levels via Logger.setLogLevel() and file output via Logger.enableFileLogging().
|
|
44
|
-
- bootstrapApplication accepts a logLevel option ('debug' | 'info' | 'none' | LogLevel[]) to control framework verbosity.
|
|
45
|
-
- Path resolution relies on RadixTree from [src/utils/radix-tree.ts](src/utils/radix-tree.ts); normalize controller and route paths to avoid duplicate slashes.
|
|
46
|
-
- Request.params are filled by Router.extractParams; Request.query carries query parameters passed from the renderer; controllers read both directly from the Request object.
|
|
47
|
-
|
|
48
|
-
## Build and Tooling
|
|
49
|
-
- Run npm run build to invoke tsup with dual ESM/CJS outputs configured in [tsup.config.ts](tsup.config.ts); the postbuild script at [scripts/postbuild.js](scripts/postbuild.js) deduplicates license banners.
|
|
50
|
-
- Node 20 or newer is required; no reflect-metadata is needed — all dependency information comes from explicit deps arrays.
|
|
51
|
-
- Source uses baseUrl ./ with tsc-alias, so prefer absolute imports like src/module/file when editing framework code to match existing style.
|
|
52
|
-
- Dist artifacts live under dist/ and are published outputs; regenerate them via the build script rather than editing directly.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
## Validating TypeScript changes
|
|
56
|
-
|
|
57
|
-
MANDATORY: Always check for compilation errors before running any tests or validation scripts, or declaring work complete, then fix all compilation errors before moving forward.
|
|
58
|
-
|
|
59
|
-
## Coding Guidelines
|
|
60
|
-
|
|
61
|
-
### Indentation
|
|
62
|
-
|
|
63
|
-
Use spaces, 4 for any file type, except yml that are 2 spaces.
|
|
64
|
-
|
|
65
|
-
### Naming Conventions
|
|
66
|
-
|
|
67
|
-
Use PascalCase for type names
|
|
68
|
-
Use PascaleCase for class names and interfaces
|
|
69
|
-
Prefix interface names by an 'I'
|
|
70
|
-
Use PascalCase for enum values
|
|
71
|
-
Choose wisely enum over union types or consts
|
|
72
|
-
Prefer interfaces over types when possible
|
|
73
|
-
Use camelCase for function and method names
|
|
74
|
-
Use camelCase for property names and local variables
|
|
75
|
-
Use whole words in names when possible
|
|
76
|
-
Use kebab-case for file names, and avoid using the same name for multiple files in different directories to prevent confusion
|
|
77
|
-
suffix file names with their type (e.g., .service.ts, .controller.ts, .component.ts) to make it clear what the file contains and its role in the architecture
|
|
78
|
-
|
|
79
|
-
### Types
|
|
80
|
-
|
|
81
|
-
Do not export types or functions unless you need to share it across multiple components
|
|
82
|
-
Do not introduce new types or values to the global namespace unless they are truly global concepts
|
|
83
|
-
|
|
84
|
-
### Comments
|
|
85
|
-
|
|
86
|
-
Use JSDoc style comments for functions, interfaces, enums, and classes
|
|
87
|
-
Always include a description of what the function/class/interface/enum does, its parameters, its return value and an example (if applicable)
|
|
88
|
-
Use inline comments to explain why a particular implementation was chosen, especially if it's not obvious. Avoid stating what the code is doing, and instead focus on the reasoning behind it.
|
|
89
|
-
|
|
90
|
-
### Strings
|
|
91
|
-
|
|
92
|
-
Always use "double quotes" for strings.
|
|
93
|
-
Use template literals for string interpolation and multi-line strings instead of concatenation.
|
|
94
|
-
|
|
95
|
-
### Style
|
|
96
|
-
|
|
97
|
-
Use arrow functions => over anonymous function expressions.
|
|
98
|
-
Only surround arrow function parameters when necessary.
|
|
99
|
-
Only surround arrow function bodies with curly braces when they are not a direct return of an expression.
|
|
100
|
-
Always surround loop and conditional bodies with curly braces.
|
|
101
|
-
Open curly braces always go on the same line as whatever necessitates them
|
|
102
|
-
Use StrouStrup style for control statements (the else is on a new line after the closing brace of the if).
|
|
103
|
-
Whenever possible, use in top-level scopes export function x(…) {…} instead of export const x = (…) => {…}. One advantage of using the function keyword is that the stack-trace shows a good name when debugging.
|
|
104
|
-
|
|
105
|
-
### Code Quality
|
|
106
|
-
|
|
107
|
-
All files must include the NoxFly copyright header
|
|
108
|
-
Prefer async and await over Promise and then calls
|
|
109
|
-
Always await a promise to make the function appearable in the stack trace, unless you have a good reason not to (e.g., you want it to run in the background and don't care about errors).
|
|
110
|
-
Look for existing test patterns before creating new structures
|
|
111
|
-
Prefer regex capture groups with names over numbered capture groups.
|
|
112
|
-
If you create any temporary new files, scripts, or helper files for iteration, clean up these files by removing them at the end of the task
|
|
113
|
-
Never duplicate imports. Always reuse existing imports if they are present.
|
|
114
|
-
When removing an import, do not leave behind blank lines where the import was. Ensure the surrounding code remains compact.
|
|
115
|
-
Do not use any or unknown as the type for variables, parameters, or return values unless absolutely necessary. If they need type annotations, they should have proper types or interfaces defined.
|
|
116
|
-
Do not duplicate code. Always look for existing utility functions, helpers, or patterns in the codebase before implementing new functionality. Reuse and extend existing code whenever possible.
|
|
117
|
-
Avoid using bind(), call() and apply() solely to control this or partially apply arguments; prefer arrow functions or closures to capture the necessary context, and use these methods only when required by an API or interoperability.
|
|
118
|
-
Always think for the most performant code for future scalability, even if it requires more upfront work. Consider time and space complexity when designing algorithms and data structures, and prefer efficient patterns that will scale well as the codebase grows.
|
|
119
|
-
Always specify the `public`, `private`, or `protected` access modifier for class members, even if the default is public. This improves readability and makes the intended encapsulation clear to other developers.
|
|
120
|
-
Always use explicit return types for functions and methods, even when TypeScript can infer them. This improves readability and helps catch unintended return values or changes in the function's behavior over time.
|
|
121
|
-
Avoid using non-null assertions (!). Instead, handle potential null or undefined values explicitly through type guards, default values, or proper error handling to ensure safer and more robust code.
|
|
122
|
-
Always prefer composition over inheritance. Favor creating small, reusable functions and classes that can be combined to achieve complex behavior, rather than relying on deep inheritance hierarchies which can lead to tight coupling and reduced flexibility.
|
|
123
|
-
Always use strict equality (=== and !==) instead of loose equality (== and !=) to avoid unexpected type coercion and ensure more predictable comparisons.
|
|
124
|
-
Always ensure readme and copilot-instructions files are updated to reflect any architectural, structural, or convention changes made to the codebase. These documents serve as the primary reference for other developers and must accurately represent the current state of the project.
|
|
125
|
-
Do not hesitate to refactor existing code to improve readability, maintainability, or performance, even if it is not directly related to the task at hand. Continuous improvement of the codebase is essential for long-term success and developer satisfaction.
|
|
126
|
-
Do not hesitate to ask for help or clarification if a request is unclear.
|
|
127
|
-
Do not hesitate to suggest improvements or optimizations if you see an opportunity, even if it's outside the scope of your current task.
|
|
128
|
-
Always write unit tests for new functionality and bug fixes, and ensure existing tests are updated as necessary to reflect changes in the codebase. Aim for high test coverage and meaningful test cases that validate the expected behavior of the code.
|
package/.vscode/settings.json
DELETED
package/AGENTS.md
DELETED
package/eslint.config.js
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
// @ts-nocheck
|
|
2
|
-
const eslint = require("@eslint/js");
|
|
3
|
-
const tseslint = require("typescript-eslint");
|
|
4
|
-
const stylistic = require("@stylistic/eslint-plugin");
|
|
5
|
-
|
|
6
|
-
module.exports = tseslint.config(
|
|
7
|
-
{
|
|
8
|
-
files: ["src/**/*.ts"],
|
|
9
|
-
extends: [
|
|
10
|
-
eslint.configs.recommended,
|
|
11
|
-
...tseslint.configs.recommended,
|
|
12
|
-
...tseslint.configs.stylistic,
|
|
13
|
-
],
|
|
14
|
-
languageOptions: {
|
|
15
|
-
parserOptions: {
|
|
16
|
-
ecmaVersion: 2020,
|
|
17
|
-
sourceType: "module",
|
|
18
|
-
project: ["./tsconfig.json"],
|
|
19
|
-
tsconfigRootDir: __dirname,
|
|
20
|
-
}
|
|
21
|
-
},
|
|
22
|
-
plugins: {
|
|
23
|
-
"@stylistic": stylistic,
|
|
24
|
-
},
|
|
25
|
-
rules: {
|
|
26
|
-
"@typescript-eslint/no-empty-object-type": "off",
|
|
27
|
-
|
|
28
|
-
"@typescript-eslint/no-require-imports": "off",
|
|
29
|
-
|
|
30
|
-
"@typescript-eslint/explicit-member-accessibility": [
|
|
31
|
-
"error",
|
|
32
|
-
{
|
|
33
|
-
"overrides": {
|
|
34
|
-
"constructors": "no-public",
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
],
|
|
38
|
-
"@typescript-eslint/explicit-function-return-type": [
|
|
39
|
-
"error",
|
|
40
|
-
{
|
|
41
|
-
"allowExpressions": true,
|
|
42
|
-
"allowHigherOrderFunctions": true,
|
|
43
|
-
"allowIIFEs": true,
|
|
44
|
-
}
|
|
45
|
-
],
|
|
46
|
-
"@typescript-eslint/consistent-type-definitions": "off",
|
|
47
|
-
"@typescript-eslint/no-explicit-any": "off",
|
|
48
|
-
"@typescript-eslint/no-inferrable-types": "off",
|
|
49
|
-
"@typescript-eslint/no-empty-function": "off",
|
|
50
|
-
"@typescript-eslint/no-unused-vars": "off",
|
|
51
|
-
"@typescript-eslint/no-namespace": "off",
|
|
52
|
-
"@typescript-eslint/no-unsafe-function-type": "off",
|
|
53
|
-
"@typescript-eslint/prefer-readonly": "warn",
|
|
54
|
-
|
|
55
|
-
"@stylistic/object-curly-spacing": ["warn", "always"],
|
|
56
|
-
"@stylistic/no-whitespace-before-property": "error",
|
|
57
|
-
"@stylistic/space-before-blocks": ["warn", "always"],
|
|
58
|
-
"@stylistic/comma-spacing": [
|
|
59
|
-
"warn",
|
|
60
|
-
{
|
|
61
|
-
"before": false,
|
|
62
|
-
"after": true
|
|
63
|
-
}
|
|
64
|
-
],
|
|
65
|
-
"@stylistic/block-spacing": ["warn", "always"],
|
|
66
|
-
"@stylistic/brace-style": [
|
|
67
|
-
"error",
|
|
68
|
-
"stroustrup",
|
|
69
|
-
{
|
|
70
|
-
"allowSingleLine": true
|
|
71
|
-
}
|
|
72
|
-
],
|
|
73
|
-
"@stylistic/function-call-spacing": ["error", "never"],
|
|
74
|
-
"@stylistic/arrow-spacing": "error",
|
|
75
|
-
"@stylistic/computed-property-spacing": "warn",
|
|
76
|
-
"@stylistic/generator-star-spacing": "error",
|
|
77
|
-
"@stylistic/indent": ["error", 4, { "SwitchCase": 1 }],
|
|
78
|
-
"@stylistic/semi": [2, "always"],
|
|
79
|
-
"@stylistic/no-extra-semi": "warn",
|
|
80
|
-
"@stylistic/semi-spacing": "warn",
|
|
81
|
-
"@stylistic/quotes": "off",
|
|
82
|
-
"@stylistic/keyword-spacing": [
|
|
83
|
-
"warn",
|
|
84
|
-
{
|
|
85
|
-
"overrides": {
|
|
86
|
-
"if": { "after": false },
|
|
87
|
-
"for": { "after": false },
|
|
88
|
-
"catch": { "after": false },
|
|
89
|
-
"while": { "after": false },
|
|
90
|
-
"as": { "after": false },
|
|
91
|
-
"switch": { "after": false }
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
],
|
|
95
|
-
|
|
96
|
-
"eqeqeq": "error",
|
|
97
|
-
"no-duplicate-imports": "error",
|
|
98
|
-
"no-empty": "off",
|
|
99
|
-
"no-empty-function": "off",
|
|
100
|
-
"no-extra-boolean-cast": "off",
|
|
101
|
-
"no-inner-declarations": "off",
|
|
102
|
-
"no-unsafe-finally": "off",
|
|
103
|
-
"no-unsafe-optional-chaining": "error",
|
|
104
|
-
"no-unused-vars": "off",
|
|
105
|
-
"no-var": "error",
|
|
106
|
-
"no-useless-catch": "off",
|
|
107
|
-
},
|
|
108
|
-
},
|
|
109
|
-
);
|
package/scripts/postbuild.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
const fs = require('fs');
|
|
2
|
-
const path = require('path');
|
|
3
|
-
|
|
4
|
-
function uniqueDocBlocks(filepath) {
|
|
5
|
-
if(!fs.existsSync(filepath)) {
|
|
6
|
-
return;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
const content = fs.readFileSync(filepath, 'utf8');
|
|
10
|
-
|
|
11
|
-
const reg = /\/\*\*[\t ]*\n(?: \*.*\n)*? \* *@copyright.*\n(?: \*.*\n)*? \*\/\n?/gm;
|
|
12
|
-
|
|
13
|
-
let first = true;
|
|
14
|
-
const deduped = content.replace(reg, (match) => {
|
|
15
|
-
if (first) {
|
|
16
|
-
first = false;
|
|
17
|
-
return match; // keep the first
|
|
18
|
-
}
|
|
19
|
-
return ''; // remove others
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
fs.writeFileSync(filepath, deduped);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const distDir = path.join(__dirname, '../dist');
|
|
26
|
-
|
|
27
|
-
for(const filename of fs.readdirSync(distDir)) {
|
|
28
|
-
if(filename.endsWith('.d.ts') || filename.endsWith('.d.mts')) {
|
|
29
|
-
uniqueDocBlocks(path.join(distDir, filename));
|
|
30
|
-
}
|
|
31
|
-
}
|
package/src/DI/app-injector.ts
DELETED
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @copyright 2025 NoxFly
|
|
3
|
-
* @license MIT
|
|
4
|
-
* @author NoxFly
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { ForwardReference } from '../utils/forward-ref';
|
|
8
|
-
import { Type } from '../utils/types';
|
|
9
|
-
import { Token, TokenKey } from './token';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Lifetime of a binding in the DI container.
|
|
13
|
-
* - singleton: created once, shared for the lifetime of the app.
|
|
14
|
-
* - scope: created once per request scope.
|
|
15
|
-
* - transient: new instance every time it is resolved.
|
|
16
|
-
*/
|
|
17
|
-
export type Lifetime = 'singleton' | 'scope' | 'transient';
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Internal representation of a registered binding.
|
|
21
|
-
*/
|
|
22
|
-
export interface IBinding<T = unknown> {
|
|
23
|
-
lifetime: Lifetime;
|
|
24
|
-
implementation: Type<T>;
|
|
25
|
-
/** Explicit constructor dependencies, declared by the class itself. */
|
|
26
|
-
deps: ReadonlyArray<TokenKey>;
|
|
27
|
-
instance?: T;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function keyOf<T>(k: TokenKey<T>): Type<T> | Token<T> {
|
|
31
|
-
return k;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* AppInjector is the core DI container.
|
|
36
|
-
* It no longer uses reflect-metadata — all dependency information
|
|
37
|
-
* comes from explicitly declared `deps` arrays on each binding.
|
|
38
|
-
*/
|
|
39
|
-
export class AppInjector {
|
|
40
|
-
public readonly bindings = new Map<Type<unknown> | Token<unknown>, IBinding<unknown>>();
|
|
41
|
-
public readonly singletons = new Map<Type<unknown> | Token<unknown>, unknown>();
|
|
42
|
-
public readonly scoped = new Map<Type<unknown> | Token<unknown>, unknown>();
|
|
43
|
-
|
|
44
|
-
constructor(public readonly name: string | null = null) {}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Creates a child scope for per-request lifetime resolution.
|
|
48
|
-
*/
|
|
49
|
-
public createScope(): AppInjector {
|
|
50
|
-
const scope = new AppInjector();
|
|
51
|
-
(scope as any).bindings = this.bindings;
|
|
52
|
-
(scope as any).singletons = this.singletons;
|
|
53
|
-
return scope;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Registers a binding explicitly.
|
|
58
|
-
*/
|
|
59
|
-
public register<T>(
|
|
60
|
-
key: TokenKey<T>,
|
|
61
|
-
implementation: Type<T>,
|
|
62
|
-
lifetime: Lifetime,
|
|
63
|
-
deps: ReadonlyArray<TokenKey> = [],
|
|
64
|
-
): void {
|
|
65
|
-
const k = keyOf(key) as TokenKey<unknown>;
|
|
66
|
-
if (!this.bindings.has(k)) {
|
|
67
|
-
this.bindings.set(k, { lifetime, implementation: implementation as Type<unknown>, deps });
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Resolves a dependency by token or class reference.
|
|
73
|
-
*/
|
|
74
|
-
public resolve<T>(target: TokenKey<T> | ForwardReference<T>): T {
|
|
75
|
-
if (target instanceof ForwardReference) {
|
|
76
|
-
return this._resolveForwardRef(target);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const k = keyOf(target) as TokenKey<unknown>;
|
|
80
|
-
|
|
81
|
-
if (this.singletons.has(k)) {
|
|
82
|
-
return this.singletons.get(k) as T;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const binding = this.bindings.get(k);
|
|
86
|
-
|
|
87
|
-
if (!binding) {
|
|
88
|
-
const name = target instanceof Token
|
|
89
|
-
? target.description
|
|
90
|
-
: (target as Type<unknown>).name
|
|
91
|
-
?? 'unknown';
|
|
92
|
-
|
|
93
|
-
throw new Error(
|
|
94
|
-
`[Noxus DI] No binding found for "${name}".\n`
|
|
95
|
-
+ `Did you forget to declare it in @Injectable({ deps }) or in bootstrapApplication({ singletons })?`,
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
switch (binding.lifetime) {
|
|
100
|
-
case 'transient':
|
|
101
|
-
return this._instantiate(binding) as T;
|
|
102
|
-
|
|
103
|
-
case 'scope': {
|
|
104
|
-
if (this.scoped.has(k)) return this.scoped.get(k) as T;
|
|
105
|
-
const inst = this._instantiate(binding);
|
|
106
|
-
this.scoped.set(k, inst);
|
|
107
|
-
return inst as T;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
case 'singleton': {
|
|
111
|
-
if (this.singletons.has(k)) return this.singletons.get(k) as T;
|
|
112
|
-
const inst = this._instantiate(binding);
|
|
113
|
-
this.singletons.set(k, inst);
|
|
114
|
-
if (binding.instance === undefined) {
|
|
115
|
-
(binding as IBinding<unknown>).instance = inst as unknown;
|
|
116
|
-
}
|
|
117
|
-
return inst as T;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// -------------------------------------------------------------------------
|
|
123
|
-
|
|
124
|
-
private _resolveForwardRef<T>(ref: ForwardReference<T>): T {
|
|
125
|
-
let resolved: T | undefined;
|
|
126
|
-
return new Proxy({} as object, {
|
|
127
|
-
get: (_obj, prop, receiver) => {
|
|
128
|
-
resolved ??= this.resolve(ref.forwardRefFn()) as T;
|
|
129
|
-
const value = Reflect.get(resolved as object, prop, receiver);
|
|
130
|
-
return typeof value === 'function' ? (value as Function).bind(resolved) : value;
|
|
131
|
-
},
|
|
132
|
-
set: (_obj, prop, value, receiver) => {
|
|
133
|
-
resolved ??= this.resolve(ref.forwardRefFn()) as T;
|
|
134
|
-
return Reflect.set(resolved as object, prop, value, receiver);
|
|
135
|
-
},
|
|
136
|
-
getPrototypeOf: () => {
|
|
137
|
-
resolved ??= this.resolve(ref.forwardRefFn()) as T;
|
|
138
|
-
return Object.getPrototypeOf(resolved);
|
|
139
|
-
},
|
|
140
|
-
}) as T;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
private _instantiate<T>(binding: IBinding<T>): T {
|
|
144
|
-
const resolvedDeps = binding.deps.map((dep) => this.resolve(dep));
|
|
145
|
-
return new binding.implementation(...resolvedDeps) as T;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* The global root injector. All singletons live here.
|
|
151
|
-
*/
|
|
152
|
-
export const RootInjector = new AppInjector('root');
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* Resets the root injector to a clean state.
|
|
156
|
-
* **Intended for testing only** — clears all bindings, singletons, and scoped instances
|
|
157
|
-
* so that each test can start from a fresh DI container without restarting the process.
|
|
158
|
-
*/
|
|
159
|
-
export function resetRootInjector(): void {
|
|
160
|
-
RootInjector.bindings.clear();
|
|
161
|
-
RootInjector.singletons.clear();
|
|
162
|
-
RootInjector.scoped.clear();
|
|
163
|
-
// Lazy import to avoid circular dependency (InjectorExplorer → app-injector → InjectorExplorer)
|
|
164
|
-
const { InjectorExplorer } = require('./injector-explorer') as typeof import('./injector-explorer');
|
|
165
|
-
InjectorExplorer.reset();
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Convenience function: resolve a token from the root injector.
|
|
170
|
-
*/
|
|
171
|
-
export function inject<T>(t: TokenKey<T> | ForwardReference<T>): T {
|
|
172
|
-
return RootInjector.resolve(t);
|
|
173
|
-
}
|
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @copyright 2025 NoxFly
|
|
3
|
-
* @license MIT
|
|
4
|
-
* @author NoxFly
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { Lifetime, RootInjector } from './app-injector';
|
|
8
|
-
import { TokenKey } from './token';
|
|
9
|
-
import { Type } from '../utils/types';
|
|
10
|
-
import { Logger } from '../utils/logger';
|
|
11
|
-
import { Guard } from '../decorators/guards.decorator';
|
|
12
|
-
import { Middleware } from '../decorators/middleware.decorator';
|
|
13
|
-
|
|
14
|
-
export interface PendingRegistration {
|
|
15
|
-
key: TokenKey;
|
|
16
|
-
implementation: Type<unknown>;
|
|
17
|
-
lifetime: Lifetime;
|
|
18
|
-
deps: ReadonlyArray<TokenKey>;
|
|
19
|
-
isController: boolean;
|
|
20
|
-
pathPrefix?: string;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Callback invoked for each controller registration discovered during flush.
|
|
25
|
-
* Decouples InjectorExplorer from the Router to avoid circular imports.
|
|
26
|
-
*/
|
|
27
|
-
export type ControllerRegistrar = (
|
|
28
|
-
controllerClass: Type<unknown>,
|
|
29
|
-
pathPrefix: string,
|
|
30
|
-
routeGuards: Guard[],
|
|
31
|
-
routeMiddlewares: Middleware[],
|
|
32
|
-
) => void;
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* InjectorExplorer accumulates registrations emitted by decorators
|
|
36
|
-
* at import time, then flushes them in two phases (bind → resolve)
|
|
37
|
-
* once bootstrapApplication triggers processing.
|
|
38
|
-
*
|
|
39
|
-
* Because deps are now explicit arrays (no reflect-metadata), this class
|
|
40
|
-
* no longer needs to introspect constructor parameter types.
|
|
41
|
-
*/
|
|
42
|
-
export class InjectorExplorer {
|
|
43
|
-
private static readonly pending: PendingRegistration[] = [];
|
|
44
|
-
private static processed = false;
|
|
45
|
-
private static accumulating = false;
|
|
46
|
-
private static loadingLock: Promise<void> = Promise.resolve();
|
|
47
|
-
private static controllerRegistrar: ControllerRegistrar | null = null;
|
|
48
|
-
|
|
49
|
-
// -------------------------------------------------------------------------
|
|
50
|
-
// Public API
|
|
51
|
-
// -------------------------------------------------------------------------
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Sets the callback used to register controllers.
|
|
55
|
-
* Must be called once before processPending (typically by bootstrapApplication).
|
|
56
|
-
*/
|
|
57
|
-
public static setControllerRegistrar(registrar: ControllerRegistrar): void {
|
|
58
|
-
InjectorExplorer.controllerRegistrar = registrar;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
public static enqueue(reg: PendingRegistration): void {
|
|
62
|
-
if (InjectorExplorer.processed && !InjectorExplorer.accumulating) {
|
|
63
|
-
InjectorExplorer._registerImmediate(reg);
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
InjectorExplorer.pending.push(reg);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Two-phase flush of all pending registrations collected at startup.
|
|
71
|
-
* Called by bootstrapApplication after app.whenReady().
|
|
72
|
-
*/
|
|
73
|
-
public static processPending(singletonOverrides?: Map<TokenKey, unknown>): void {
|
|
74
|
-
const queue = [...InjectorExplorer.pending];
|
|
75
|
-
InjectorExplorer.pending.length = 0;
|
|
76
|
-
|
|
77
|
-
InjectorExplorer._phaseOne(queue);
|
|
78
|
-
InjectorExplorer._phaseTwo(queue, singletonOverrides);
|
|
79
|
-
|
|
80
|
-
InjectorExplorer.processed = true;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** Enters accumulation mode for lazy-loaded batches. */
|
|
84
|
-
public static beginAccumulate(): void {
|
|
85
|
-
InjectorExplorer.accumulating = true;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Exits accumulation mode and flushes queued registrations
|
|
90
|
-
* with the same two-phase guarantee as processPending.
|
|
91
|
-
* Serialised through a lock to prevent concurrent lazy loads from corrupting the queue.
|
|
92
|
-
*/
|
|
93
|
-
public static flushAccumulated(
|
|
94
|
-
routeGuards: Guard[] = [],
|
|
95
|
-
routeMiddlewares: Middleware[] = [],
|
|
96
|
-
pathPrefix = '',
|
|
97
|
-
): Promise<void> {
|
|
98
|
-
InjectorExplorer.loadingLock = InjectorExplorer.loadingLock.then(() => {
|
|
99
|
-
InjectorExplorer.accumulating = false;
|
|
100
|
-
const queue = [...InjectorExplorer.pending];
|
|
101
|
-
InjectorExplorer.pending.length = 0;
|
|
102
|
-
InjectorExplorer._phaseOne(queue);
|
|
103
|
-
|
|
104
|
-
// Stamp the path prefix on controller registrations
|
|
105
|
-
for (const reg of queue) {
|
|
106
|
-
if (reg.isController) reg.pathPrefix = pathPrefix;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
InjectorExplorer._phaseTwo(queue, undefined, routeGuards, routeMiddlewares);
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
return InjectorExplorer.loadingLock;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Returns a Promise that resolves once all pending flushAccumulated calls
|
|
117
|
-
* have completed. Useful for awaiting lazy-load serialisation.
|
|
118
|
-
*/
|
|
119
|
-
public static waitForFlush(): Promise<void> {
|
|
120
|
-
return InjectorExplorer.loadingLock;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Resets the explorer state. Intended for tests only.
|
|
125
|
-
*/
|
|
126
|
-
public static reset(): void {
|
|
127
|
-
InjectorExplorer.pending.length = 0;
|
|
128
|
-
InjectorExplorer.processed = false;
|
|
129
|
-
InjectorExplorer.accumulating = false;
|
|
130
|
-
InjectorExplorer.loadingLock = Promise.resolve();
|
|
131
|
-
InjectorExplorer.controllerRegistrar = null;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// -------------------------------------------------------------------------
|
|
135
|
-
// Private helpers
|
|
136
|
-
// -------------------------------------------------------------------------
|
|
137
|
-
|
|
138
|
-
/** Phase 1: register all bindings without instantiating anything. */
|
|
139
|
-
private static _phaseOne(queue: PendingRegistration[]): void {
|
|
140
|
-
for (const reg of queue) {
|
|
141
|
-
RootInjector.register(reg.key, reg.implementation, reg.lifetime, reg.deps);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** Phase 2: validate deps, resolve singletons and register controllers via the registrar callback. */
|
|
146
|
-
private static _phaseTwo(
|
|
147
|
-
queue: PendingRegistration[],
|
|
148
|
-
overrides?: Map<TokenKey, unknown>,
|
|
149
|
-
routeGuards: Guard[] = [],
|
|
150
|
-
routeMiddlewares: Middleware[] = [],
|
|
151
|
-
): void {
|
|
152
|
-
// Early dependency validation: warn about deps that have no binding
|
|
153
|
-
for (const reg of queue) {
|
|
154
|
-
for (const dep of reg.deps) {
|
|
155
|
-
if (!RootInjector.bindings.has(dep as any) && !RootInjector.singletons.has(dep as any)) {
|
|
156
|
-
Logger.warn(`[Noxus DI] "${reg.implementation.name}" declares dep "${(dep as any).name ?? dep}" which has no binding`);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
for (const reg of queue) {
|
|
162
|
-
// Apply value overrides (e.g. singleton instances provided via bootstrapApplication config)
|
|
163
|
-
if (overrides?.has(reg.key)) {
|
|
164
|
-
const override = overrides.get(reg.key);
|
|
165
|
-
RootInjector.singletons.set(reg.key as any, override);
|
|
166
|
-
Logger.log(`Registered ${reg.implementation.name} as singleton (overridden)`);
|
|
167
|
-
continue;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
if (reg.lifetime === 'singleton') {
|
|
171
|
-
RootInjector.resolve(reg.key);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
if (reg.isController) {
|
|
175
|
-
if (!InjectorExplorer.controllerRegistrar) {
|
|
176
|
-
throw new Error('[Noxus DI] No controller registrar set. Call InjectorExplorer.setControllerRegistrar() before processing.');
|
|
177
|
-
}
|
|
178
|
-
InjectorExplorer.controllerRegistrar(
|
|
179
|
-
reg.implementation,
|
|
180
|
-
reg.pathPrefix ?? '',
|
|
181
|
-
routeGuards,
|
|
182
|
-
routeMiddlewares,
|
|
183
|
-
);
|
|
184
|
-
} else if (reg.lifetime !== 'singleton') {
|
|
185
|
-
Logger.log(`Registered ${reg.implementation.name} as ${reg.lifetime}`);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
private static _registerImmediate(reg: PendingRegistration): void {
|
|
191
|
-
RootInjector.register(reg.key, reg.implementation, reg.lifetime, reg.deps);
|
|
192
|
-
|
|
193
|
-
if (reg.lifetime === 'singleton') {
|
|
194
|
-
RootInjector.resolve(reg.key);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
if (reg.isController && InjectorExplorer.controllerRegistrar) {
|
|
198
|
-
InjectorExplorer.controllerRegistrar(reg.implementation, '', [], []);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
}
|