@lithia-js/core 1.0.0-canary.0

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.
Files changed (91) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/CHANGELOG.md +13 -0
  3. package/LICENSE +21 -0
  4. package/README.md +60 -0
  5. package/dist/config.d.ts +101 -0
  6. package/dist/config.js +113 -0
  7. package/dist/config.js.map +1 -0
  8. package/dist/context/event-context.d.ts +53 -0
  9. package/dist/context/event-context.js +42 -0
  10. package/dist/context/event-context.js.map +1 -0
  11. package/dist/context/index.d.ts +16 -0
  12. package/dist/context/index.js +29 -0
  13. package/dist/context/index.js.map +1 -0
  14. package/dist/context/lithia-context.d.ts +47 -0
  15. package/dist/context/lithia-context.js +43 -0
  16. package/dist/context/lithia-context.js.map +1 -0
  17. package/dist/context/route-context.d.ts +74 -0
  18. package/dist/context/route-context.js +42 -0
  19. package/dist/context/route-context.js.map +1 -0
  20. package/dist/env.d.ts +1 -0
  21. package/dist/env.js +32 -0
  22. package/dist/env.js.map +1 -0
  23. package/dist/errors.d.ts +51 -0
  24. package/dist/errors.js +80 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/hooks/dependency-hooks.d.ts +105 -0
  27. package/dist/hooks/dependency-hooks.js +96 -0
  28. package/dist/hooks/dependency-hooks.js.map +1 -0
  29. package/dist/hooks/event-hooks.d.ts +61 -0
  30. package/dist/hooks/event-hooks.js +70 -0
  31. package/dist/hooks/event-hooks.js.map +1 -0
  32. package/dist/hooks/index.d.ts +41 -0
  33. package/dist/hooks/index.js +59 -0
  34. package/dist/hooks/index.js.map +1 -0
  35. package/dist/hooks/route-hooks.d.ts +154 -0
  36. package/dist/hooks/route-hooks.js +174 -0
  37. package/dist/hooks/route-hooks.js.map +1 -0
  38. package/dist/lib.d.ts +10 -0
  39. package/dist/lib.js +30 -0
  40. package/dist/lib.js.map +1 -0
  41. package/dist/lithia.d.ts +447 -0
  42. package/dist/lithia.js +649 -0
  43. package/dist/lithia.js.map +1 -0
  44. package/dist/logger.d.ts +11 -0
  45. package/dist/logger.js +55 -0
  46. package/dist/logger.js.map +1 -0
  47. package/dist/module-loader.d.ts +12 -0
  48. package/dist/module-loader.js +78 -0
  49. package/dist/module-loader.js.map +1 -0
  50. package/dist/server/event-processor.d.ts +195 -0
  51. package/dist/server/event-processor.js +253 -0
  52. package/dist/server/event-processor.js.map +1 -0
  53. package/dist/server/http-server.d.ts +196 -0
  54. package/dist/server/http-server.js +295 -0
  55. package/dist/server/http-server.js.map +1 -0
  56. package/dist/server/middlewares/validation.d.ts +12 -0
  57. package/dist/server/middlewares/validation.js +34 -0
  58. package/dist/server/middlewares/validation.js.map +1 -0
  59. package/dist/server/request-processor.d.ts +400 -0
  60. package/dist/server/request-processor.js +652 -0
  61. package/dist/server/request-processor.js.map +1 -0
  62. package/dist/server/request.d.ts +73 -0
  63. package/dist/server/request.js +207 -0
  64. package/dist/server/request.js.map +1 -0
  65. package/dist/server/response.d.ts +69 -0
  66. package/dist/server/response.js +173 -0
  67. package/dist/server/response.js.map +1 -0
  68. package/package.json +46 -0
  69. package/src/config.ts +212 -0
  70. package/src/context/event-context.ts +66 -0
  71. package/src/context/index.ts +32 -0
  72. package/src/context/lithia-context.ts +59 -0
  73. package/src/context/route-context.ts +89 -0
  74. package/src/env.ts +31 -0
  75. package/src/errors.ts +96 -0
  76. package/src/hooks/dependency-hooks.ts +122 -0
  77. package/src/hooks/event-hooks.ts +69 -0
  78. package/src/hooks/index.ts +58 -0
  79. package/src/hooks/route-hooks.ts +177 -0
  80. package/src/lib.ts +27 -0
  81. package/src/lithia.ts +777 -0
  82. package/src/logger.ts +66 -0
  83. package/src/module-loader.ts +45 -0
  84. package/src/server/event-processor.ts +344 -0
  85. package/src/server/http-server.ts +371 -0
  86. package/src/server/middlewares/validation.ts +46 -0
  87. package/src/server/request-processor.ts +860 -0
  88. package/src/server/request.ts +247 -0
  89. package/src/server/response.ts +204 -0
  90. package/tsconfig.build.tsbuildinfo +1 -0
  91. package/tsconfig.json +8 -0
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ /**
3
+ * Route context module for HTTP requests.
4
+ *
5
+ * Provides context specific to HTTP route handling, including access to
6
+ * the current request, response, and matched route information.
7
+ *
8
+ * @module context/route-context
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.routeContext = void 0;
12
+ exports.getRouteContext = getRouteContext;
13
+ const node_async_hooks_1 = require("node:async_hooks");
14
+ /**
15
+ * AsyncLocalStorage instance for route context.
16
+ *
17
+ * Uses Node.js AsyncLocalStorage to provide implicit context propagation
18
+ * for HTTP request handling across async boundaries.
19
+ *
20
+ * @see https://nodejs.org/api/async_hooks.html#class-asynclocalstorage
21
+ */
22
+ exports.routeContext = new node_async_hooks_1.AsyncLocalStorage();
23
+ /**
24
+ * Gets the current route context.
25
+ *
26
+ * @returns The current RouteContext
27
+ * @throws {Error} If called outside of an HTTP request handler
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * const ctx = getRouteContext();
32
+ * console.log(ctx.req.method, ctx.req.url);
33
+ * ```
34
+ */
35
+ function getRouteContext() {
36
+ const ctx = exports.routeContext.getStore();
37
+ if (!ctx) {
38
+ throw new Error("Lithia route context not found. Are you calling a hook outside of a request handler?");
39
+ }
40
+ return ctx;
41
+ }
42
+ //# sourceMappingURL=route-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-context.js","sourceRoot":"","sources":["../../src/context/route-context.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAyEH,0CAQC;AA/ED,uDAAqD;AAiDrD;;;;;;;GAOG;AACU,QAAA,YAAY,GAAG,IAAI,oCAAiB,EAAgB,CAAC;AAElE;;;;;;;;;;;GAWG;AACH,SAAgB,eAAe;IAC9B,MAAM,GAAG,GAAG,oBAAY,CAAC,QAAQ,EAAE,CAAC;IACpC,IAAI,CAAC,GAAG,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACd,sFAAsF,CACtF,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"}
package/dist/env.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function loadEnv(cwd: string): Record<string, string>;
package/dist/env.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadEnv = loadEnv;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const dotenv_1 = require("dotenv");
7
+ function loadEnv(cwd) {
8
+ const envFiles = [".env", ".env.local"];
9
+ const envVars = {};
10
+ for (const file of envFiles) {
11
+ const filePath = (0, node_path_1.resolve)(cwd, file);
12
+ if ((0, node_fs_1.existsSync)(filePath)) {
13
+ try {
14
+ const parsed = (0, dotenv_1.parse)((0, node_fs_1.readFileSync)(filePath));
15
+ Object.assign(envVars, parsed);
16
+ }
17
+ catch {
18
+ // Ignore errors parsing env file
19
+ }
20
+ }
21
+ }
22
+ // Apply variables to process.env, but don't overwrite existing ones
23
+ for (const key in envVars) {
24
+ if (Object.hasOwn(envVars, key)) {
25
+ if (process.env[key] === undefined) {
26
+ process.env[key] = envVars[key];
27
+ }
28
+ }
29
+ }
30
+ return envVars;
31
+ }
32
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":";;AAIA,0BA0BC;AA9BD,qCAAmD;AACnD,yCAAoC;AACpC,mCAA+B;AAE/B,SAAgB,OAAO,CAAC,GAAW;IAClC,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACxC,MAAM,OAAO,GAA2B,EAAE,CAAC;IAE3C,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;QAC7B,MAAM,QAAQ,GAAG,IAAA,mBAAO,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACpC,IAAI,IAAA,oBAAU,EAAC,QAAQ,CAAC,EAAE,CAAC;YAC1B,IAAI,CAAC;gBACJ,MAAM,MAAM,GAAG,IAAA,cAAK,EAAC,IAAA,sBAAY,EAAC,QAAQ,CAAC,CAAC,CAAC;gBAC7C,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YAChC,CAAC;YAAC,MAAM,CAAC;gBACR,iCAAiC;YAClC,CAAC;QACF,CAAC;IACF,CAAC;IAED,oEAAoE;IACpE,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC3B,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;YACjC,IAAI,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE,CAAC;gBACpC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;YACjC,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,OAAO,CAAC;AAChB,CAAC"}
@@ -0,0 +1,51 @@
1
+ /** Possible severity levels for a `LithiaError`. */
2
+ export type LithiaErrorLevel = "fatal" | "error" | "warning" | "info";
3
+ /** Base error class for Lithia runtime errors.
4
+ *
5
+ * All custom runtime errors extend `LithiaError` and provide a machine
6
+ * readable `code` and a `level` used for logging and control-flow (for
7
+ * instance `fatal` errors may terminate the process).
8
+ */
9
+ export declare class LithiaError extends Error {
10
+ /** Machine-readable error code. */
11
+ code: string;
12
+ /** Severity level. */
13
+ level: LithiaErrorLevel;
14
+ /** Optional underlying cause. */
15
+ cause?: any | undefined;
16
+ constructor(
17
+ /** Machine-readable error code. */
18
+ code: string, message: string,
19
+ /** Severity level. */
20
+ level?: LithiaErrorLevel,
21
+ /** Optional underlying cause. */
22
+ cause?: any | undefined);
23
+ }
24
+ /** Error raised when the manifest version does not match the native schema. */
25
+ export declare class SchemaVersionMismatchError extends LithiaError {
26
+ constructor(expected: string, received: string);
27
+ }
28
+ /** Error used when reading or parsing the manifest fails. */
29
+ export declare class ManifestLoadError extends LithiaError {
30
+ constructor(cause: any);
31
+ }
32
+ /** Error raised when serving a static file but no MIME type is configured for its extension. */
33
+ export declare class StaticFileMimeMissingError extends LithiaError {
34
+ constructor(extension: string, filePath: string);
35
+ }
36
+ /** Error raised when request data validation fails. */
37
+ export declare class ValidationError extends LithiaError {
38
+ issues?: any[] | undefined;
39
+ constructor(message: string, issues?: any[] | undefined);
40
+ }
41
+ /** Error raised when a route module does not export a default async function. */
42
+ export declare class InvalidRouteModuleError extends LithiaError {
43
+ constructor(filePath: string, reason: string);
44
+ }
45
+ export declare class InvalidEventModuleError extends LithiaError {
46
+ constructor(filePath: string, reason: string);
47
+ }
48
+ /** Error raised when the server bootstrap module (_server.ts) is invalid. */
49
+ export declare class InvalidBootstrapModuleError extends LithiaError {
50
+ constructor(filePath: string, reason: string);
51
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvalidBootstrapModuleError = exports.InvalidEventModuleError = exports.InvalidRouteModuleError = exports.ValidationError = exports.StaticFileMimeMissingError = exports.ManifestLoadError = exports.SchemaVersionMismatchError = exports.LithiaError = void 0;
4
+ /** Base error class for Lithia runtime errors.
5
+ *
6
+ * All custom runtime errors extend `LithiaError` and provide a machine
7
+ * readable `code` and a `level` used for logging and control-flow (for
8
+ * instance `fatal` errors may terminate the process).
9
+ */
10
+ class LithiaError extends Error {
11
+ code;
12
+ level;
13
+ cause;
14
+ constructor(
15
+ /** Machine-readable error code. */
16
+ code, message,
17
+ /** Severity level. */
18
+ level = "error",
19
+ /** Optional underlying cause. */
20
+ cause) {
21
+ super(message);
22
+ this.code = code;
23
+ this.level = level;
24
+ this.cause = cause;
25
+ this.name = "LithiaError";
26
+ Error.captureStackTrace?.(this, this.constructor);
27
+ }
28
+ }
29
+ exports.LithiaError = LithiaError;
30
+ /** Error raised when the manifest version does not match the native schema. */
31
+ class SchemaVersionMismatchError extends LithiaError {
32
+ constructor(expected, received) {
33
+ super("SCHEMA_VERSION_MISMATCH", `Manifest version ${received} does not match expected version ${expected}`, "fatal", undefined);
34
+ }
35
+ }
36
+ exports.SchemaVersionMismatchError = SchemaVersionMismatchError;
37
+ /** Error used when reading or parsing the manifest fails. */
38
+ class ManifestLoadError extends LithiaError {
39
+ constructor(cause) {
40
+ super("MANIFEST_LOAD_ERROR", "Failed to load manifest.", "fatal", cause);
41
+ }
42
+ }
43
+ exports.ManifestLoadError = ManifestLoadError;
44
+ /** Error raised when serving a static file but no MIME type is configured for its extension. */
45
+ class StaticFileMimeMissingError extends LithiaError {
46
+ constructor(extension, filePath) {
47
+ super("STATIC_FILE_MIME_MISSING", `No MIME type configured for extension '${extension}' when serving '${filePath}'. Please configure a MIME type for this extension in your Lithia config.`, "error");
48
+ }
49
+ }
50
+ exports.StaticFileMimeMissingError = StaticFileMimeMissingError;
51
+ /** Error raised when request data validation fails. */
52
+ class ValidationError extends LithiaError {
53
+ issues;
54
+ constructor(message, issues) {
55
+ super("VALIDATION_ERROR", message, "error");
56
+ this.issues = issues;
57
+ }
58
+ }
59
+ exports.ValidationError = ValidationError;
60
+ /** Error raised when a route module does not export a default async function. */
61
+ class InvalidRouteModuleError extends LithiaError {
62
+ constructor(filePath, reason) {
63
+ super("INVALID_ROUTE_MODULE", `Invalid route module at '${filePath}': ${reason}. Route modules must export a default async function.`, "error");
64
+ }
65
+ }
66
+ exports.InvalidRouteModuleError = InvalidRouteModuleError;
67
+ class InvalidEventModuleError extends LithiaError {
68
+ constructor(filePath, reason) {
69
+ super("INVALID_EVENT_MODULE", `Invalid event module at '${filePath}': ${reason}. Event modules must export a default function that accepts a Lithia instance.`, "error");
70
+ }
71
+ }
72
+ exports.InvalidEventModuleError = InvalidEventModuleError;
73
+ /** Error raised when the server bootstrap module (_server.ts) is invalid. */
74
+ class InvalidBootstrapModuleError extends LithiaError {
75
+ constructor(filePath, reason) {
76
+ super("INVALID_BOOTSTRAP_MODULE", `Invalid server bootstrap module at '${filePath}': ${reason}. The module must export a default async function.`, "fatal");
77
+ }
78
+ }
79
+ exports.InvalidBootstrapModuleError = InvalidBootstrapModuleError;
80
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAGA;;;;;GAKG;AACH,MAAa,WAAY,SAAQ,KAAK;IAG7B;IAGA;IAEA;IAPR;IACC,mCAAmC;IAC5B,IAAY,EACnB,OAAe;IACf,sBAAsB;IACf,QAA0B,OAAO;IACxC,iCAAiC;IAC1B,KAAW;QAElB,KAAK,CAAC,OAAO,CAAC,CAAC;QAPR,SAAI,GAAJ,IAAI,CAAQ;QAGZ,UAAK,GAAL,KAAK,CAA4B;QAEjC,UAAK,GAAL,KAAK,CAAM;QAGlB,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,KAAK,CAAC,iBAAiB,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,WAAkB,CAAC,CAAC;IAC1D,CAAC;CACD;AAdD,kCAcC;AAED,+EAA+E;AAC/E,MAAa,0BAA2B,SAAQ,WAAW;IAC1D,YAAY,QAAgB,EAAE,QAAgB;QAC7C,KAAK,CACJ,yBAAyB,EACzB,oBAAoB,QAAQ,oCAAoC,QAAQ,EAAE,EAC1E,OAAO,EACP,SAAS,CACT,CAAC;IACH,CAAC;CACD;AATD,gEASC;AAED,6DAA6D;AAC7D,MAAa,iBAAkB,SAAQ,WAAW;IACjD,YAAY,KAAU;QACrB,KAAK,CAAC,qBAAqB,EAAE,0BAA0B,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IAC1E,CAAC;CACD;AAJD,8CAIC;AAED,gGAAgG;AAChG,MAAa,0BAA2B,SAAQ,WAAW;IAC1D,YAAY,SAAiB,EAAE,QAAgB;QAC9C,KAAK,CACJ,0BAA0B,EAC1B,0CAA0C,SAAS,mBAAmB,QAAQ,2EAA2E,EACzJ,OAAO,CACP,CAAC;IACH,CAAC;CACD;AARD,gEAQC;AAED,uDAAuD;AACvD,MAAa,eAAgB,SAAQ,WAAW;IAGvC;IAFR,YACC,OAAe,EACR,MAAc;QAErB,KAAK,CAAC,kBAAkB,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAFrC,WAAM,GAAN,MAAM,CAAQ;IAGtB,CAAC;CACD;AAPD,0CAOC;AAED,iFAAiF;AACjF,MAAa,uBAAwB,SAAQ,WAAW;IACvD,YAAY,QAAgB,EAAE,MAAc;QAC3C,KAAK,CACJ,sBAAsB,EACtB,4BAA4B,QAAQ,MAAM,MAAM,uDAAuD,EACvG,OAAO,CACP,CAAC;IACH,CAAC;CACD;AARD,0DAQC;AAED,MAAa,uBAAwB,SAAQ,WAAW;IACvD,YAAY,QAAgB,EAAE,MAAc;QAC3C,KAAK,CACJ,sBAAsB,EACtB,4BAA4B,QAAQ,MAAM,MAAM,gFAAgF,EAChI,OAAO,CACP,CAAC;IACH,CAAC;CACD;AARD,0DAQC;AAED,6EAA6E;AAC7E,MAAa,2BAA4B,SAAQ,WAAW;IAC3D,YAAY,QAAgB,EAAE,MAAc;QAC3C,KAAK,CACJ,0BAA0B,EAC1B,uCAAuC,QAAQ,MAAM,MAAM,oDAAoD,EAC/G,OAAO,CACP,CAAC;IACH,CAAC;CACD;AARD,kEAQC"}
@@ -0,0 +1,105 @@
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
+ * Unique key for dependency injection.
14
+ *
15
+ * Can be:
16
+ * - A Symbol (recommended for type safety and uniqueness)
17
+ * - A string (simple but can conflict)
18
+ * - A class constructor (for class-based dependencies)
19
+ *
20
+ * @template T - Type of the dependency value
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * // Using Symbol (recommended)
25
+ * const dbKey = createInjectionKey<Database>('database');
26
+ *
27
+ * // Using string
28
+ * const dbKey = 'database';
29
+ *
30
+ * // Using class
31
+ * class Database {}
32
+ * const dbKey = Database;
33
+ * ```
34
+ */
35
+ export type InjectionKey<T> = symbol | string | {
36
+ new (...args: any[]): T;
37
+ };
38
+ /**
39
+ * Provides a dependency for injection.
40
+ *
41
+ * Registers a dependency in the current context's DI container.
42
+ * Should typically be called in middlewares or during application bootstrap.
43
+ *
44
+ * Dependencies are available for the entire lifecycle of the current
45
+ * request or event.
46
+ *
47
+ * @param key - Unique key to identify the dependency
48
+ * @param value - The dependency value to provide
49
+ * @template T - Type of the dependency value
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * // In a middleware
54
+ * export default async function authMiddleware(req, res, next) {
55
+ * const user = await authenticate(req);
56
+ * provide(userKey, user);
57
+ * await next();
58
+ * }
59
+ * ```
60
+ */
61
+ export declare function provide<T>(key: InjectionKey<T>, value: T): void;
62
+ /**
63
+ * Injects a dependency from the DI container.
64
+ *
65
+ * Retrieves a previously provided dependency. Throws an error if the
66
+ * dependency was not provided.
67
+ *
68
+ * @param key - The key of the dependency to inject
69
+ * @returns The dependency value
70
+ * @throws {Error} If the dependency is not found in the container
71
+ * @template T - Type of the dependency value
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * export default async function handler() {
76
+ * const db = inject(dbKey);
77
+ * const users = await db.query('SELECT * FROM users');
78
+ * return users;
79
+ * }
80
+ * ```
81
+ */
82
+ export declare function inject<T>(key: InjectionKey<T>): T;
83
+ /**
84
+ * Injects a dependency, returning undefined if not found.
85
+ *
86
+ * Like `inject()`, but returns undefined instead of throwing when the
87
+ * dependency is not available. Useful for optional dependencies.
88
+ *
89
+ * @param key - The key of the dependency to inject
90
+ * @returns The dependency value, or undefined if not found
91
+ * @template T - Type of the dependency value
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * export default async function handler() {
96
+ * const user = injectOptional(userKey);
97
+ * if (user) {
98
+ * console.log('Authenticated as:', user.name);
99
+ * } else {
100
+ * console.log('Anonymous user');
101
+ * }
102
+ * }
103
+ * ```
104
+ */
105
+ export declare function injectOptional<T>(key: InjectionKey<T>): T | undefined;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ /**
3
+ * Dependency injection hooks for Lithia.
4
+ *
5
+ * Provides a simple but powerful dependency injection system that works
6
+ * across both HTTP request handlers and Socket.IO event handlers.
7
+ *
8
+ * Dependencies can be provided globally (via `lithia.provide()`) or
9
+ * scoped to a specific request/event (via `provide()` in middlewares).
10
+ *
11
+ * @module hooks/dependency-hooks
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.provide = provide;
15
+ exports.inject = inject;
16
+ exports.injectOptional = injectOptional;
17
+ const lithia_context_1 = require("../context/lithia-context");
18
+ /**
19
+ * Provides a dependency for injection.
20
+ *
21
+ * Registers a dependency in the current context's DI container.
22
+ * Should typically be called in middlewares or during application bootstrap.
23
+ *
24
+ * Dependencies are available for the entire lifecycle of the current
25
+ * request or event.
26
+ *
27
+ * @param key - Unique key to identify the dependency
28
+ * @param value - The dependency value to provide
29
+ * @template T - Type of the dependency value
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * // In a middleware
34
+ * export default async function authMiddleware(req, res, next) {
35
+ * const user = await authenticate(req);
36
+ * provide(userKey, user);
37
+ * await next();
38
+ * }
39
+ * ```
40
+ */
41
+ function provide(key, value) {
42
+ (0, lithia_context_1.getLithiaContext)().dependencies.set(key, value);
43
+ }
44
+ /**
45
+ * Injects a dependency from the DI container.
46
+ *
47
+ * Retrieves a previously provided dependency. Throws an error if the
48
+ * dependency was not provided.
49
+ *
50
+ * @param key - The key of the dependency to inject
51
+ * @returns The dependency value
52
+ * @throws {Error} If the dependency is not found in the container
53
+ * @template T - Type of the dependency value
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * export default async function handler() {
58
+ * const db = inject(dbKey);
59
+ * const users = await db.query('SELECT * FROM users');
60
+ * return users;
61
+ * }
62
+ * ```
63
+ */
64
+ function inject(key) {
65
+ const context = (0, lithia_context_1.getLithiaContext)();
66
+ if (!context.dependencies.has(key)) {
67
+ throw new Error(`Dependency not found: ${String(key)}. Make sure to provide it using 'provide()' in a middleware.`);
68
+ }
69
+ return context.dependencies.get(key);
70
+ }
71
+ /**
72
+ * Injects a dependency, returning undefined if not found.
73
+ *
74
+ * Like `inject()`, but returns undefined instead of throwing when the
75
+ * dependency is not available. Useful for optional dependencies.
76
+ *
77
+ * @param key - The key of the dependency to inject
78
+ * @returns The dependency value, or undefined if not found
79
+ * @template T - Type of the dependency value
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * export default async function handler() {
84
+ * const user = injectOptional(userKey);
85
+ * if (user) {
86
+ * console.log('Authenticated as:', user.name);
87
+ * } else {
88
+ * console.log('Anonymous user');
89
+ * }
90
+ * }
91
+ * ```
92
+ */
93
+ function injectOptional(key) {
94
+ return (0, lithia_context_1.getLithiaContext)().dependencies.get(key);
95
+ }
96
+ //# sourceMappingURL=dependency-hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dependency-hooks.js","sourceRoot":"","sources":["../../src/hooks/dependency-hooks.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;AAqDH,0BAEC;AAsBD,wBAQC;AAwBD,wCAEC;AA7GD,8DAA6D;AA4B7D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,OAAO,CAAI,GAAoB,EAAE,KAAQ;IACxD,IAAA,iCAAgB,GAAE,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;AACjD,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,MAAM,CAAI,GAAoB;IAC7C,MAAM,OAAO,GAAG,IAAA,iCAAgB,GAAE,CAAC;IACnC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;QACpC,MAAM,IAAI,KAAK,CACd,yBAAyB,MAAM,CAAC,GAAG,CAAC,8DAA8D,CAClG,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAM,CAAC;AAC3C,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,SAAgB,cAAc,CAAI,GAAoB;IACrD,OAAO,IAAA,iCAAgB,GAAE,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAkB,CAAC;AAClE,CAAC"}
@@ -0,0 +1,61 @@
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
+ import type { Socket } from "socket.io";
10
+ /**
11
+ * Accesses the data payload sent with a Socket.IO event.
12
+ *
13
+ * Returns the data that the client sent when emitting the event.
14
+ * The structure and type of the data depends on what the client sends.
15
+ *
16
+ * @returns The event data payload
17
+ * @throws {Error} If called outside of an event handler
18
+ * @template T - Type of the event data
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * // Handler for 'chat:message' event
23
+ * export default async function handler() {
24
+ * const data = useData<{ message: string; userId: string }>();
25
+ * console.log('Received message:', data.message);
26
+ * console.log('From user:', data.userId);
27
+ * }
28
+ * ```
29
+ */
30
+ export declare function useData<T>(): T;
31
+ /**
32
+ * Accesses the Socket.IO socket instance for the current event.
33
+ *
34
+ * Returns the socket that triggered the event, allowing you to emit
35
+ * messages back to the client, join/leave rooms, or access socket metadata.
36
+ *
37
+ * @returns The Socket.IO socket instance
38
+ * @throws {Error} If called outside of an event handler
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // Handler for 'chat:message' event
43
+ * export default async function handler() {
44
+ * const socket = useSocket();
45
+ * const data = useData<{ message: string }>();
46
+ *
47
+ * // Emit response back to the client
48
+ * socket.emit('message:received', { success: true });
49
+ *
50
+ * // Broadcast to other clients
51
+ * socket.broadcast.emit('new:message', data);
52
+ *
53
+ * // Join a room
54
+ * socket.join('chat-room');
55
+ *
56
+ * // Access socket metadata
57
+ * console.log('Socket ID:', socket.id);
58
+ * }
59
+ * ```
60
+ */
61
+ export declare function useSocket(): Socket;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /**
3
+ * Socket.IO event hooks for Lithia.
4
+ *
5
+ * Provides hooks to access event-specific data in Socket.IO event handlers.
6
+ * All hooks must be called within a Socket.IO event handler.
7
+ *
8
+ * @module hooks/event-hooks
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.useData = useData;
12
+ exports.useSocket = useSocket;
13
+ const event_context_1 = require("../context/event-context");
14
+ /**
15
+ * Accesses the data payload sent with a Socket.IO event.
16
+ *
17
+ * Returns the data that the client sent when emitting the event.
18
+ * The structure and type of the data depends on what the client sends.
19
+ *
20
+ * @returns The event data payload
21
+ * @throws {Error} If called outside of an event handler
22
+ * @template T - Type of the event data
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * // Handler for 'chat:message' event
27
+ * export default async function handler() {
28
+ * const data = useData<{ message: string; userId: string }>();
29
+ * console.log('Received message:', data.message);
30
+ * console.log('From user:', data.userId);
31
+ * }
32
+ * ```
33
+ */
34
+ function useData() {
35
+ return (0, event_context_1.getEventContext)().data;
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
+ function useSocket() {
68
+ return (0, event_context_1.getEventContext)().socket;
69
+ }
70
+ //# sourceMappingURL=event-hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-hooks.js","sourceRoot":"","sources":["../../src/hooks/event-hooks.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AAyBH,0BAEC;AAgCD,8BAEC;AA1DD,4DAA2D;AAE3D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,OAAO;IACtB,OAAO,IAAA,+BAAe,GAAE,CAAC,IAAS,CAAC;AACpC,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,SAAgB,SAAS;IACxB,OAAO,IAAA,+BAAe,GAAE,CAAC,MAAM,CAAC;AACjC,CAAC"}
@@ -0,0 +1,41 @@
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
+ export { type InjectionKey, inject, injectOptional, provide, } from "./dependency-hooks";
40
+ export { useData } from "./event-hooks";
41
+ export { useHeaders, useParams, useQuery, useRequest, useResponse, useRoute, useSocketServer, } from "./route-hooks";
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * Lithia hooks for accessing context and dependencies.
4
+ *
5
+ * This module provides a composable API for accessing request/event data
6
+ * and managing dependencies through dependency injection.
7
+ *
8
+ * ## Hook Categories
9
+ *
10
+ * ### Route Hooks (HTTP Requests)
11
+ * - `useRequest()`: Access the current request object
12
+ * - `useResponse()`: Access the current response object
13
+ * - `useRoute()`: Access the matched route metadata
14
+ * - `useParams()`: Access route parameters (e.g., `/users/:id`)
15
+ * - `useQuery()`: Access URL query parameters
16
+ * - `useHeaders()`: Access request headers
17
+ *
18
+ * ### Event Hooks (Socket.IO)
19
+ * - `useData()`: Access event payload data
20
+ *
21
+ * ### Dependency Injection Hooks (Both)
22
+ * - `provide()`: Register a dependency in the container
23
+ * - `inject()`: Retrieve a required dependency
24
+ * - `injectOptional()`: Retrieve an optional dependency
25
+ *
26
+ * @module hooks
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { useParams, inject } from '@lithia-js/core';
31
+ *
32
+ * export default async function handler() {
33
+ * const { id } = useParams<{ id: string }>();
34
+ * const db = inject(dbKey);
35
+ * const user = await db.findUser(id);
36
+ * return user;
37
+ * }
38
+ * ```
39
+ */
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.useSocketServer = exports.useRoute = exports.useResponse = exports.useRequest = exports.useQuery = exports.useParams = exports.useHeaders = exports.useData = exports.provide = exports.injectOptional = exports.inject = void 0;
42
+ // Dependency injection hooks
43
+ var dependency_hooks_1 = require("./dependency-hooks");
44
+ Object.defineProperty(exports, "inject", { enumerable: true, get: function () { return dependency_hooks_1.inject; } });
45
+ Object.defineProperty(exports, "injectOptional", { enumerable: true, get: function () { return dependency_hooks_1.injectOptional; } });
46
+ Object.defineProperty(exports, "provide", { enumerable: true, get: function () { return dependency_hooks_1.provide; } });
47
+ // Socket.IO event hooks
48
+ var event_hooks_1 = require("./event-hooks");
49
+ Object.defineProperty(exports, "useData", { enumerable: true, get: function () { return event_hooks_1.useData; } });
50
+ // HTTP Route hooks
51
+ var route_hooks_1 = require("./route-hooks");
52
+ Object.defineProperty(exports, "useHeaders", { enumerable: true, get: function () { return route_hooks_1.useHeaders; } });
53
+ Object.defineProperty(exports, "useParams", { enumerable: true, get: function () { return route_hooks_1.useParams; } });
54
+ Object.defineProperty(exports, "useQuery", { enumerable: true, get: function () { return route_hooks_1.useQuery; } });
55
+ Object.defineProperty(exports, "useRequest", { enumerable: true, get: function () { return route_hooks_1.useRequest; } });
56
+ Object.defineProperty(exports, "useResponse", { enumerable: true, get: function () { return route_hooks_1.useResponse; } });
57
+ Object.defineProperty(exports, "useRoute", { enumerable: true, get: function () { return route_hooks_1.useRoute; } });
58
+ Object.defineProperty(exports, "useSocketServer", { enumerable: true, get: function () { return route_hooks_1.useSocketServer; } });
59
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;;;AAEH,6BAA6B;AAC7B,uDAK4B;AAH3B,0GAAA,MAAM,OAAA;AACN,kHAAA,cAAc,OAAA;AACd,2GAAA,OAAO,OAAA;AAER,wBAAwB;AACxB,6CAAwC;AAA/B,sGAAA,OAAO,OAAA;AAChB,mBAAmB;AACnB,6CAQuB;AAPtB,yGAAA,UAAU,OAAA;AACV,wGAAA,SAAS,OAAA;AACT,uGAAA,QAAQ,OAAA;AACR,yGAAA,UAAU,OAAA;AACV,0GAAA,WAAW,OAAA;AACX,uGAAA,QAAQ,OAAA;AACR,8GAAA,eAAe,OAAA"}