@lithia-js/core 1.0.0-canary.2 → 1.0.0-canary.3

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.
@@ -1,122 +0,0 @@
1
- /**
2
- * Dependency injection hooks for Lithia.
3
- *
4
- * Provides a simple but powerful dependency injection system that works
5
- * across both HTTP request handlers and Socket.IO event handlers.
6
- *
7
- * Dependencies can be provided globally (via `lithia.provide()`) or
8
- * scoped to a specific request/event (via `provide()` in middlewares).
9
- *
10
- * @module hooks/dependency-hooks
11
- */
12
-
13
- import { getLithiaContext } from "../context/lithia-context";
14
-
15
- /**
16
- * Unique key for dependency injection.
17
- *
18
- * Can be:
19
- * - A Symbol (recommended for type safety and uniqueness)
20
- * - A string (simple but can conflict)
21
- * - A class constructor (for class-based dependencies)
22
- *
23
- * @template T - Type of the dependency value
24
- *
25
- * @example
26
- * ```typescript
27
- * // Using Symbol (recommended)
28
- * const dbKey = createInjectionKey<Database>('database');
29
- *
30
- * // Using string
31
- * const dbKey = 'database';
32
- *
33
- * // Using class
34
- * class Database {}
35
- * const dbKey = Database;
36
- * ```
37
- */
38
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
- export type InjectionKey<T> = symbol | string | { new (...args: any[]): T };
40
-
41
- /**
42
- * Provides a dependency for injection.
43
- *
44
- * Registers a dependency in the current context's DI container.
45
- * Should typically be called in middlewares or during application bootstrap.
46
- *
47
- * Dependencies are available for the entire lifecycle of the current
48
- * request or event.
49
- *
50
- * @param key - Unique key to identify the dependency
51
- * @param value - The dependency value to provide
52
- * @template T - Type of the dependency value
53
- *
54
- * @example
55
- * ```typescript
56
- * // In a middleware
57
- * export default async function authMiddleware(req, res, next) {
58
- * const user = await authenticate(req);
59
- * provide(userKey, user);
60
- * await next();
61
- * }
62
- * ```
63
- */
64
- export function provide<T>(key: InjectionKey<T>, value: T): void {
65
- getLithiaContext().dependencies.set(key, value);
66
- }
67
-
68
- /**
69
- * Injects a dependency from the DI container.
70
- *
71
- * Retrieves a previously provided dependency. Throws an error if the
72
- * dependency was not provided.
73
- *
74
- * @param key - The key of the dependency to inject
75
- * @returns The dependency value
76
- * @throws {Error} If the dependency is not found in the container
77
- * @template T - Type of the dependency value
78
- *
79
- * @example
80
- * ```typescript
81
- * export default async function handler() {
82
- * const db = inject(dbKey);
83
- * const users = await db.query('SELECT * FROM users');
84
- * return users;
85
- * }
86
- * ```
87
- */
88
- export function inject<T>(key: InjectionKey<T>): T {
89
- const context = getLithiaContext();
90
- if (!context.dependencies.has(key)) {
91
- throw new Error(
92
- `Dependency not found: ${String(key)}. Make sure to provide it using 'provide()' in a middleware.`,
93
- );
94
- }
95
- return context.dependencies.get(key) as T;
96
- }
97
-
98
- /**
99
- * Injects a dependency, returning undefined if not found.
100
- *
101
- * Like `inject()`, but returns undefined instead of throwing when the
102
- * dependency is not available. Useful for optional dependencies.
103
- *
104
- * @param key - The key of the dependency to inject
105
- * @returns The dependency value, or undefined if not found
106
- * @template T - Type of the dependency value
107
- *
108
- * @example
109
- * ```typescript
110
- * export default async function handler() {
111
- * const user = injectOptional(userKey);
112
- * if (user) {
113
- * console.log('Authenticated as:', user.name);
114
- * } else {
115
- * console.log('Anonymous user');
116
- * }
117
- * }
118
- * ```
119
- */
120
- export function injectOptional<T>(key: InjectionKey<T>): T | undefined {
121
- return getLithiaContext().dependencies.get(key) as T | undefined;
122
- }
@@ -1,69 +0,0 @@
1
- /**
2
- * Socket.IO event hooks for Lithia.
3
- *
4
- * Provides hooks to access event-specific data in Socket.IO event handlers.
5
- * All hooks must be called within a Socket.IO event handler.
6
- *
7
- * @module hooks/event-hooks
8
- */
9
-
10
- import type { Socket } from "socket.io";
11
- import { getEventContext } from "../context/event-context";
12
-
13
- /**
14
- * Accesses the data payload sent with a Socket.IO event.
15
- *
16
- * Returns the data that the client sent when emitting the event.
17
- * The structure and type of the data depends on what the client sends.
18
- *
19
- * @returns The event data payload
20
- * @throws {Error} If called outside of an event handler
21
- * @template T - Type of the event data
22
- *
23
- * @example
24
- * ```typescript
25
- * // Handler for 'chat:message' event
26
- * export default async function handler() {
27
- * const data = useData<{ message: string; userId: string }>();
28
- * console.log('Received message:', data.message);
29
- * console.log('From user:', data.userId);
30
- * }
31
- * ```
32
- */
33
- export function useData<T>(): T {
34
- return getEventContext().data as T;
35
- }
36
-
37
- /**
38
- * Accesses the Socket.IO socket instance for the current event.
39
- *
40
- * Returns the socket that triggered the event, allowing you to emit
41
- * messages back to the client, join/leave rooms, or access socket metadata.
42
- *
43
- * @returns The Socket.IO socket instance
44
- * @throws {Error} If called outside of an event handler
45
- *
46
- * @example
47
- * ```typescript
48
- * // Handler for 'chat:message' event
49
- * export default async function handler() {
50
- * const socket = useSocket();
51
- * const data = useData<{ message: string }>();
52
- *
53
- * // Emit response back to the client
54
- * socket.emit('message:received', { success: true });
55
- *
56
- * // Broadcast to other clients
57
- * socket.broadcast.emit('new:message', data);
58
- *
59
- * // Join a room
60
- * socket.join('chat-room');
61
- *
62
- * // Access socket metadata
63
- * console.log('Socket ID:', socket.id);
64
- * }
65
- * ```
66
- */
67
- export function useSocket(): Socket {
68
- return getEventContext().socket;
69
- }
@@ -1,58 +0,0 @@
1
- /**
2
- * Lithia hooks for accessing context and dependencies.
3
- *
4
- * This module provides a composable API for accessing request/event data
5
- * and managing dependencies through dependency injection.
6
- *
7
- * ## Hook Categories
8
- *
9
- * ### Route Hooks (HTTP Requests)
10
- * - `useRequest()`: Access the current request object
11
- * - `useResponse()`: Access the current response object
12
- * - `useRoute()`: Access the matched route metadata
13
- * - `useParams()`: Access route parameters (e.g., `/users/:id`)
14
- * - `useQuery()`: Access URL query parameters
15
- * - `useHeaders()`: Access request headers
16
- *
17
- * ### Event Hooks (Socket.IO)
18
- * - `useData()`: Access event payload data
19
- *
20
- * ### Dependency Injection Hooks (Both)
21
- * - `provide()`: Register a dependency in the container
22
- * - `inject()`: Retrieve a required dependency
23
- * - `injectOptional()`: Retrieve an optional dependency
24
- *
25
- * @module hooks
26
- *
27
- * @example
28
- * ```typescript
29
- * import { useParams, inject } from '@lithia-js/core';
30
- *
31
- * export default async function handler() {
32
- * const { id } = useParams<{ id: string }>();
33
- * const db = inject(dbKey);
34
- * const user = await db.findUser(id);
35
- * return user;
36
- * }
37
- * ```
38
- */
39
-
40
- // Dependency injection hooks
41
- export {
42
- type InjectionKey,
43
- inject,
44
- injectOptional,
45
- provide,
46
- } from "./dependency-hooks";
47
- // Socket.IO event hooks
48
- export { useData } from "./event-hooks";
49
- // HTTP Route hooks
50
- export {
51
- useHeaders,
52
- useParams,
53
- useQuery,
54
- useRequest,
55
- useResponse,
56
- useRoute,
57
- useSocketServer,
58
- } from "./route-hooks";
@@ -1,177 +0,0 @@
1
- /**
2
- * HTTP route hooks for Lithia.
3
- *
4
- * Provides convenient hooks to access request-specific data in route handlers.
5
- * All hooks must be called within an HTTP request handler or middleware.
6
- *
7
- * @module hooks/route-hooks
8
- */
9
-
10
- import type { IncomingHttpHeaders } from "node:http";
11
- import type { Route } from "@lithia-js/native";
12
- import type { Server } from "socket.io";
13
- import { getRouteContext } from "../context/route-context";
14
- import type { LithiaRequest, Params, Query } from "../server/request";
15
- import type { LithiaResponse } from "../server/response";
16
-
17
- /**
18
- * Accesses the current HTTP request object.
19
- *
20
- * Provides access to all request properties including params, query,
21
- * headers, body, and other request metadata.
22
- *
23
- * @returns The current LithiaRequest instance
24
- * @throws {Error} If called outside of a request handler
25
- *
26
- * @example
27
- * ```typescript
28
- * export default async function handler() {
29
- * const req = useRequest();
30
- * console.log(req.method, req.url);
31
- * }
32
- * ```
33
- */
34
- export function useRequest(): LithiaRequest {
35
- return getRouteContext().req;
36
- }
37
-
38
- /**
39
- * Accesses the current HTTP response object.
40
- *
41
- * Used to send responses back to the client, set headers, status codes, etc.
42
- *
43
- * @returns The current LithiaResponse instance
44
- * @throws {Error} If called outside of a request handler
45
- *
46
- * @example
47
- * ```typescript
48
- * export default async function handler() {
49
- * const res = useResponse();
50
- * res.status(200).json({ message: 'Success' });
51
- * }
52
- * ```
53
- */
54
- export function useResponse(): LithiaResponse {
55
- return getRouteContext().res;
56
- }
57
-
58
- /**
59
- * Accesses the current matched route definition.
60
- *
61
- * Contains metadata about the current route including path pattern,
62
- * HTTP method, and handler information.
63
- *
64
- * @returns The matched Route, or undefined if no route matched or called before route resolution
65
- * @throws {Error} If called outside of a request handler
66
- *
67
- * @example
68
- * ```typescript
69
- * export default async function handler() {
70
- * const route = useRoute();
71
- * console.log('Handling route:', route?.path);
72
- * }
73
- * ```
74
- */
75
- export function useRoute(): Route | undefined {
76
- return getRouteContext().route;
77
- }
78
-
79
- /**
80
- * Accesses route parameters (dynamic segments).
81
- *
82
- * Extracts parameters from dynamic route segments like `/users/:id`.
83
- *
84
- * @returns Object containing route parameters
85
- * @throws {Error} If called outside of a request handler
86
- * @template T - Type of the params object
87
- *
88
- * @example
89
- * ```typescript
90
- * // Route: /users/:id
91
- * export default async function handler() {
92
- * const { id } = useParams<{ id: string }>();
93
- * console.log('User ID:', id);
94
- * }
95
- * ```
96
- */
97
- export function useParams<T extends Params = Params>(): T {
98
- return getRouteContext().req.params as T;
99
- }
100
-
101
- /**
102
- * Accesses URL query parameters.
103
- *
104
- * Extracts query string parameters from the request URL.
105
- *
106
- * @returns Object containing query parameters
107
- * @throws {Error} If called outside of a request handler
108
- * @template T - Type of the query object
109
- *
110
- * @example
111
- * ```typescript
112
- * // URL: /search?q=lithia&page=1
113
- * export default async function handler() {
114
- * const { q, page } = useQuery<{ q: string; page: string }>();
115
- * console.log('Search:', q, 'Page:', page);
116
- * }
117
- * ```
118
- */
119
- export function useQuery<T extends Query = Query>(): T {
120
- return getRouteContext().req.query as T;
121
- }
122
-
123
- /**
124
- * Accesses HTTP request headers.
125
- *
126
- * Returns all headers sent with the request.
127
- *
128
- * @returns Object containing HTTP headers
129
- * @throws {Error} If called outside of a request handler
130
- *
131
- * @example
132
- * ```typescript
133
- * export default async function handler() {
134
- * const headers = useHeaders();
135
- * const auth = headers.authorization;
136
- * console.log('Auth header:', auth);
137
- * }
138
- * ```
139
- */
140
- export function useHeaders(): IncomingHttpHeaders {
141
- return getRouteContext().req.headers;
142
- }
143
-
144
- /**
145
- * Accesses the Socket.IO server instance from within an HTTP route handler.
146
- *
147
- * This hook allows HTTP routes to interact with Socket.IO, enabling you to
148
- * emit events to connected clients, broadcast messages, or manage rooms in
149
- * response to HTTP requests.
150
- *
151
- * @returns The Socket.IO Server instance
152
- * @throws {Error} If called outside of a request handler
153
- *
154
- * @example
155
- * ```typescript
156
- * // HTTP route that triggers real-time updates
157
- * export default async function handler() {
158
- * const io = useSocketServer();
159
- * const { message } = useQuery<{ message: string }>();
160
- *
161
- * // Broadcast to all connected clients
162
- * io.emit('notification', { message, timestamp: Date.now() });
163
- *
164
- * // Emit to a specific room
165
- * io.to('admin-room').emit('alert', { message });
166
- *
167
- * // Get all connected sockets
168
- * const sockets = await io.fetchSockets();
169
- * console.log(`Broadcasting to ${sockets.length} clients`);
170
- *
171
- * return { success: true, clients: sockets.length };
172
- * }
173
- * ```
174
- */
175
- export function useSocketServer(): Server {
176
- return getRouteContext().socketServer;
177
- }
package/src/lib.ts DELETED
@@ -1,27 +0,0 @@
1
- export { defineConfig, LithiaConfig } from "./config";
2
- export { loadEnv } from "./env";
3
- export {
4
- InjectionKey,
5
- inject,
6
- injectOptional,
7
- provide,
8
- useData,
9
- useHeaders,
10
- useParams,
11
- useQuery,
12
- useRequest,
13
- useResponse,
14
- useRoute,
15
- useSocketServer,
16
- } from "./hooks";
17
- export { Lithia } from "./lithia";
18
- export { logger } from "./logger";
19
- export { EventErrorInfo, EventHandler } from "./server/event-processor";
20
- export { validate } from "./server/middlewares/validation";
21
- export { LithiaRequest, Params, Query } from "./server/request";
22
- export {
23
- LithiaHandler,
24
- LithiaMiddleware,
25
- RequestErrorInfo,
26
- } from "./server/request-processor";
27
- export { LithiaResponse } from "./server/response";