kuwan-expresspack-core 0.1.15 → 0.1.17

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.
@@ -0,0 +1,5 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+
3
+ var a=new AsyncLocalStorage;function n(e){return {get(t){return e.data.get(t)},set(t,o){e.data.set(t,o);},has(t){return e.data.has(t)},delete(t){return e.data.delete(t)},clear(){e.data.clear();}}}function c(){let e=a.getStore();if(!e)throw new Error("No context available. Ensure context middleware is registered before accessing context.");return n(e)}function i(){let e=a.getStore();return e?n(e):void 0}function y(e){let t={data:new Map};return a.run(t,e)}
4
+
5
+ export { a, n as b, c, i as d, y as e };
@@ -0,0 +1,12 @@
1
+ import { z as z$1 } from 'zod';
2
+ import { config } from '@dotenvx/dotenvx';
3
+ import { colorize } from 'consola/utils';
4
+ import L from 'consola';
5
+
6
+ var m=colorize;function N(r){switch(typeof r){case "number":case "bigint":return colorize("cyan",r.toString());case "boolean":return colorize(r?"green":"red",String(r));case "symbol":return colorize("magenta",r.toString());case "string":return isNaN(Number(r))?colorize("whiteBright",`${r}`):colorize("yellow",`'${r}'`);case "undefined":return colorize("gray","undefined")}return r===null?colorize("dim","null"):String(r)}var P=L.create({level:Number.isNaN(Number(process.env.EXPRESSPACK_LOG_LEVEL))?3:Number(process.env.EXPRESSPACK_LOG_LEVEL)});function b(){let r=Number(process.env.EXPRESSPACK_LOG_LEVEL);P.level=Number.isNaN(r)?3:r;}var s=P;var c,l=null,v=null,y={},E=[];function z(r,n){let o=r.safeParse(n);if(o.success)return o.data;console.error("\u274C Invalid environment variables:"),console.error(z$1.prettifyError(o.error));}function I(r,n,o={fatal:false,immediate_log_error:true,log_error_after_graceful_start:true}){if(b(),y=o,o.fatal)try{let t=r.parse(n);return {...c,...t}}catch(t){throw t instanceof z$1.ZodError?(l=z$1.prettifyError(t),v=t,s.error("\u274C Invalid environment variables:"),s.error("\u274C",l),new Error("Invalid environment variables. The environment variable did not pass the schema validation. Check if you have set all required environment variables correctly.")):t}let i=r.safeParse(n);if(!i.success){let t=r.partial().safeParse(n);if(!t.success)return l=z$1.prettifyError(i.error),v=i.error,o.immediate_log_error&&(s.error("\u274C Invalid environment variables:"),s.error("\u274C",l)),c||{};l=z$1.prettifyError(i.error),v=i.error,o.immediate_log_error&&(s.error("\u274C Invalid environment variables:"),s.error("\u274C",l));let d=r.keyof();E=d.options;for(let p of d.options)p in t.data||(t.data[p]=void 0);return {...c,...t.data}}let g=r.keyof();E=g.options;for(let t of g.options)t in i.data||(i.data[t]=void 0);return {...c,...i.data}}function R(){return v}function S(){return l}function T(r){if(!r||Object.keys(r).length===0){s.warn("No environment variables to print. Make sure the env is complete and valid.");return}let n=e=>e.startsWith("* ")?m("dim",e):e,o=e=>E.includes(e)?e:`* ${e}`,i=e=>e.startsWith("! ")?m("dim",m("yellow",`${e}`)):e,g=e=>E.includes(e)&&r[e]===void 0?`! ${e}`:e,t=Object.entries(r).sort(([e],[u])=>e.localeCompare(u)).map(([e,u])=>[o(e),u]).map(([e,u])=>[g(e),u]),d=Math.max(...t.map(([e])=>e.length))+2,p=t.map(([e,u])=>`${e.padEnd(d," ").replace(e,n(e)).replace(e,i(e))} ${N(u)}`),_=`KEY${" ".repeat(d-3)} VALUE`,h=" ".repeat(_.length);return [h,_,h,...p].join(`
7
+ `)}function C(){if(y){let{log_error_after_graceful_start:r}=y;if(r){let n=S();n&&s.error("Invalid Environment Variable Value",`
8
+ -----
9
+ ${n}
10
+ -----`);}}}function K(r){c={};let n=config(r);return b(),c=n.parsed?n.parsed:void 0,n}function $(r){return new Proxy(r,{get(n,o){return o in n?n[o]:process.env[o]}})}function j(r,n,o){let i=I(r,n,o);return $(i)}var Y={create:j,parseEnv:z,prettifyEnv:T,getEnvErrorRaw:R,getEnvErrorString:S,logEnvErrors:C,config:K};
11
+
12
+ export { s as a, I as b, R as c, S as d, T as e, C as f, K as g, Y as h };
@@ -0,0 +1,3 @@
1
+ function r(e){let n=(t,o)=>{e.appContext||(e.appContext={}),e.appContext[t]=o;};function a(t){return e.appContext?.[t]}return {set:n,get:a}}
2
+
3
+ export { r as a };
@@ -0,0 +1,3 @@
1
+ async function i(e,t){let r=await e();if(!r||!("default"in r)){let s=t?`Missing "export default" in module "${t}"`:`Missing "export default" from lazy import "${e}"`;throw new Error(s,{cause:{source:e}})}return r.default}
2
+
3
+ export { i as a };
@@ -0,0 +1,6 @@
1
+ import a from 'emittery';
2
+ import { env } from 'process';
3
+
4
+ function c(){return env.EXPRESSPACK_EVENT_EMITTER_DEBUG==="true"||env.EXPRESSPACK_EVENT_EMITTER_DEBUG==="1"||(typeof env.EXPRESSPACK_EVENT_EMITTER_DEBUG=="boolean"?env.EXPRESSPACK_EVENT_EMITTER_DEBUG===true:false)}var r=new a({debug:{name:"expresspack-emitter",enabled:c()}});function y(){return new a({debug:{name:"c-emitter",enabled:c()}})}function x(o){o({on:async(i,t)=>{typeof t=="function"&&t.length===0?r.on(i,async s=>{try{let e=await t();if(typeof e=="object"&&e!==null&&"default"in e){let f=e.default;if(typeof f=="function")return f(s)}if(typeof e=="function")return e(s)}catch(e){throw e instanceof Error?e:new Error(`Unknown error occurred in event handler for event "${t}"`)}}):(console.log(typeof t),r.on(i,t));},emitter:r});}function T(o,E){return E}var K=r;
5
+
6
+ export { r as a, y as b, x as c, T as d, K as e };
@@ -0,0 +1,140 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+
3
+ /**
4
+ * Application context with typed access methods
5
+ */
6
+ interface AppContext<TData extends Record<string, any> = Record<string, any>> {
7
+ /**
8
+ * Get a value from the context store
9
+ *
10
+ * @param key - The key to retrieve
11
+ * @returns The stored value or undefined
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * interface MyContext {
16
+ * user: { id: number; name: string };
17
+ * tenantId: string;
18
+ * }
19
+ *
20
+ * const ctx = getAppContext<MyContext>();
21
+ * const user = ctx.get('user'); // type is { id: number; name: string } | undefined
22
+ * ```
23
+ */
24
+ get<K extends keyof TData>(key: K): TData[K] | undefined;
25
+ /**
26
+ * Set a value in the context store
27
+ *
28
+ * @param key - The key to store the value under
29
+ * @param value - The value to store
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const ctx = getAppContext<MyContext>();
34
+ * ctx.set('user', { id: 1, name: 'John' }); // fully typed
35
+ * ```
36
+ */
37
+ set<K extends keyof TData>(key: K, value: TData[K]): void;
38
+ /**
39
+ * Check if a key exists in the context store
40
+ *
41
+ * @param key - The key to check
42
+ * @returns True if the key exists
43
+ */
44
+ has<K extends keyof TData>(key: K): boolean;
45
+ /**
46
+ * Delete a value from the context store
47
+ *
48
+ * @param key - The key to delete
49
+ * @returns True if the key existed and was deleted
50
+ */
51
+ delete<K extends keyof TData>(key: K): boolean;
52
+ /**
53
+ * Clear all values from the context store
54
+ */
55
+ clear(): void;
56
+ }
57
+ /**
58
+ * Internal context structure
59
+ */
60
+ interface InternalContext<TData extends Record<string, any> = Record<string, any>> {
61
+ data: Map<keyof TData, any>;
62
+ }
63
+ /**
64
+ * AsyncLocalStorage instance for managing context
65
+ */
66
+ declare const asyncLocalStorage: AsyncLocalStorage<InternalContext<any>>;
67
+ /**
68
+ * Create a typed context proxy from internal context
69
+ */
70
+ declare function createContextProxy<TData extends Record<string, any>>(internal: InternalContext<TData>): AppContext<TData>;
71
+ /**
72
+ * Get the current application context with custom type support
73
+ *
74
+ * @throws {Error} If called outside of context
75
+ * @returns {AppContext<TData>} The current context
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * import { getAppContext } from 'expresspack';
80
+ *
81
+ * interface MyContext {
82
+ * user: { id: number; name: string };
83
+ * tenantId: string;
84
+ * }
85
+ *
86
+ * export function someHandler(req, res) {
87
+ * const ctx = getAppContext<MyContext>();
88
+ *
89
+ * // Fully typed access
90
+ * const user = ctx.get('user'); // type: { id: number; name: string } | undefined
91
+ *
92
+ * // Fully typed set
93
+ * ctx.set('user', { id: 1, name: 'John' });
94
+ * }
95
+ * ```
96
+ */
97
+ declare function getAppContext<TData extends Record<string, any> = Record<string, any>>(): AppContext<TData>;
98
+ /**
99
+ * Get the current application context, returns undefined if not available
100
+ * Useful for optional context access
101
+ *
102
+ * @returns {AppContext<TData> | undefined} The current context or undefined
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * import { tryGetAppContext } from 'expresspack';
107
+ *
108
+ * export function someUtility() {
109
+ * const ctx = tryGetAppContext<MyContext>();
110
+ * if (ctx) {
111
+ * const user = ctx.get('user');
112
+ * }
113
+ * }
114
+ * ```
115
+ */
116
+ declare function tryGetAppContext<TData extends Record<string, any> = Record<string, any>>(): AppContext<TData> | undefined;
117
+ /**
118
+ * Run a function within a context (useful for testing)
119
+ *
120
+ * @param fn - The function to execute
121
+ * @returns The result of the function
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * import { runInContext } from 'expresspack';
126
+ *
127
+ * interface MyContext {
128
+ * userId: number;
129
+ * }
130
+ *
131
+ * const result = runInContext(() => {
132
+ * const ctx = getAppContext<MyContext>();
133
+ * ctx.set('userId', 123);
134
+ * return someFunction();
135
+ * });
136
+ * ```
137
+ */
138
+ declare function runInContext<T>(fn: () => T): T;
139
+
140
+ export { type AppContext, type InternalContext, asyncLocalStorage, createContextProxy, getAppContext, runInContext, tryGetAppContext };
@@ -0,0 +1 @@
1
+ export { a as asyncLocalStorage, b as createContextProxy, c as getAppContext, e as runInContext, d as tryGetAppContext } from '../../chunk-55RBYZEZ.mjs';
@@ -0,0 +1,2 @@
1
+ export { getAppContext, tryGetAppContext } from './context-store-internal.js';
2
+ import 'node:async_hooks';
@@ -0,0 +1 @@
1
+ export { c as getAppContext, d as tryGetAppContext } from '../../chunk-55RBYZEZ.mjs';
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,16 @@
1
+ import { Request } from 'express';
2
+
3
+ /**
4
+ * Simple Context - Use when AsyncLocalStorage is not needed or not available.
5
+ *
6
+ */
7
+
8
+ /**
9
+ * Helper function to set/get values in Request.
10
+ */
11
+ declare function useAppContext<TData extends Record<never, never> = Record<never, never>>(req: Request): {
12
+ set: (key: string, value: any) => void;
13
+ get: <K extends keyof TData>(key: K) => TData[K] | undefined;
14
+ };
15
+
16
+ export { useAppContext };
@@ -0,0 +1 @@
1
+ export { a as useAppContext } from '../chunk-FFCH7NYQ.mjs';
@@ -0,0 +1 @@
1
+ import '@antfu/eslint-config';
@@ -0,0 +1,3 @@
1
+ import { g } from './chunk-CZGPAGDK.mjs';
2
+
3
+ g();
package/dist/env.d.ts CHANGED
@@ -56,8 +56,9 @@ declare function prettifyEnv(env: Record<string, any>): string | undefined;
56
56
  */
57
57
  declare function logEnvErrors(): void;
58
58
  declare function config(options?: DotenvConfigOptions | undefined): DotenvConfigOutput;
59
+ declare function createProxy<T extends z.ZodObject<any>>(schema: T, data: unknown, options?: Partial<EnvOptions>): z.output<T>;
59
60
  declare const _default: {
60
- create: typeof create;
61
+ create: typeof createProxy;
61
62
  parseEnv: typeof parseEnv;
62
63
  prettifyEnv: typeof prettifyEnv;
63
64
  getEnvErrorRaw: typeof getEnvErrorRaw;
package/dist/env.mjs CHANGED
@@ -1 +1 @@
1
- export { g as config, b as create, h as default, c as getEnvErrorRaw, d as getEnvErrorString, f as logEnvErrors, e as prettifyEnv } from './chunk-AFN6MPA7.mjs';
1
+ export { g as config, b as create, h as default, c as getEnvErrorRaw, d as getEnvErrorString, f as logEnvErrors, e as prettifyEnv } from './chunk-CZGPAGDK.mjs';
package/dist/index.d.ts CHANGED
@@ -8,14 +8,27 @@ declare function gracefulShutdown(server: Server, onShutdown: () => Promise<void
8
8
  type AppContext = {
9
9
  app: Express;
10
10
  };
11
- type KernelExports = ((context: AppContext) => void) | Promise<void>;
11
+ type KernelExports = ((context: AppContext) => void) | Promise<void> | void;
12
12
  /**
13
13
  * This is mostly a plain Express middleware definition.
14
14
  *
15
15
  * We just called it "**kernel**" to avoid mixing routers
16
16
  * and main app middlewares.
17
+ * @deprecated
18
+ * This will be removed in future versions.
19
+ * Use `defineMiddlewareKernel` instead.
17
20
  */
18
21
  declare function defineKernel(def: KernelExports): KernelExports;
22
+ /**
23
+ * Defines a middleware kernel for the framework.
24
+ * Accepts a setup function that receives the app context.
25
+ * Use for registering global middleware (e.g., app.use).
26
+ */
27
+ declare function defineMiddlewareKernel(setup: (context: {
28
+ app: Express;
29
+ }) => void | Promise<void>): (context: {
30
+ app: Express;
31
+ }) => void | Promise<void>;
19
32
 
20
33
  interface AppBootstrapContext extends Record<string, any> {
21
34
  app: Express;
@@ -25,7 +38,10 @@ interface LoadKernelOptions {
25
38
  * Loads the main kernel (Express middlewares) of your application.
26
39
  *
27
40
  */
28
- kernel: () => Promise<any>;
41
+ kernel?: () => Promise<any>;
42
+ kernel2?: () => Promise<{
43
+ default: (context: AppBootstrapContext) => void | Promise<void>;
44
+ } | ((context: AppBootstrapContext) => void | Promise<void>)>;
29
45
  /**
30
46
  * Loads the event listeners for the application.
31
47
  *
@@ -47,7 +63,7 @@ interface LoadKernelOptions {
47
63
  }
48
64
  declare function loadKernel({ app }: {
49
65
  app: any;
50
- }, { kernel, listener, appBootstrap, }: LoadKernelOptions): Promise<void>;
66
+ }, options: LoadKernelOptions): Promise<void>;
51
67
 
52
68
  declare function createRouter(options?: RouterOptions): Router;
53
69
 
@@ -56,7 +72,7 @@ declare function createRouter(options?: RouterOptions): Router;
56
72
  * @param fn Callback to register routes on the router
57
73
  * @returns Express Router instance
58
74
  */
59
- declare function defineRouterMiddleware(fn: (router: Router) => void, options?: RouterOptions): Router;
75
+ declare function defineRouterMiddleware(fn: (r: Router) => void, options?: RouterOptions): Router;
60
76
 
61
77
  /**
62
78
  * Load all configurations from the config directory
@@ -66,4 +82,4 @@ declare function defineRouterMiddleware(fn: (router: Router) => void, options?:
66
82
  */
67
83
  declare function configLoader(root: string): Promise<void>;
68
84
 
69
- export { type AppBootstrapContext, type AppContext, type KernelExports, type LoadKernelOptions, configLoader, createRouter, defineKernel, defineRouterMiddleware, gracefulHTTPStart, gracefulShutdown, loadKernel };
85
+ export { type AppBootstrapContext, type AppContext, type KernelExports, type LoadKernelOptions, configLoader, createRouter, defineKernel, defineMiddlewareKernel, defineRouterMiddleware, gracefulHTTPStart, gracefulShutdown, loadKernel };
package/dist/index.mjs CHANGED
@@ -1,14 +1,15 @@
1
- import { c } from './chunk-CRIPGIHI.mjs';
2
- import { a as a$1 } from './chunk-VSPZT4K6.mjs';
3
- import { a, f } from './chunk-AFN6MPA7.mjs';
1
+ import { e } from './chunk-OXUMMLIO.mjs';
2
+ import { a as a$1 } from './chunk-JKH5TYED.mjs';
3
+ import { a as a$2 } from './chunk-VSPZT4K6.mjs';
4
+ import { a, f } from './chunk-CZGPAGDK.mjs';
4
5
  import { Router } from 'express';
5
- import N, { relative, join } from 'path';
6
+ import M, { relative, join } from 'path';
6
7
  import { existsSync } from 'fs';
7
8
  import { glob } from 'tinyglobby';
8
9
  import { pathToFileURL } from 'url';
9
10
 
10
- function T(r,n,e){return r.listen(n,async()=>{e&&(a.debug("Executing onStart hook..."),await e().catch(o=>{a.error("Error during onStart hook:",o);})),a.box({message:`Server is running at http://localhost:${n}`,style:{borderColor:"cyan"},level:"info"});try{await c.emit("app:mounted");}catch(o){a.error("Error during app:mounted event:",o);}finally{f();}})}function k(r,n){process.on("SIGINT",async()=>{a.info("Received SIGINT. Shutting down gracefully..."),await new Promise(e=>{r.close(async i=>i instanceof Error?(a.error("Error shutting down server:",i),e()):(n&&await n().catch(o=>{a.error("Error during shutdown hook:",o);}),a.info("Server has been shut down."),e()));}),process.exit(0);});}function L(r){return r}async function $({app:r},{kernel:n,listener:e,appBootstrap:i}){a.debug("Loading kernel...");try{let o=await n();await(o?.default||o)({app:r});}catch(o){throw a.error("Error loading kernel:",o),o}if(e&&typeof e=="function")try{let o=await e(),a$1=o?.default||o;a$1===void 0||typeof a$1!="function"?a.warn("No listener setup function found"):await a$1();}catch(o){throw a.error("Error loading listener:",o),o}if(i&&typeof i=="function")try{await i({app:r});}catch(o){throw a.error("Error during boot process:",o),o}a.debug("Kernel loaded.");}function g(r){return Router(r)}function K(r,n){let e=g(n);return r(e),e}function P(r){let n=join(r,"expresspack.config"),e=join(r,"app"),i=join(r,"config"),o=join(i,"app"),a=join(i,"body-parser"),f=join(e,"controllers"),l=join(e,"services"),d=join(e,"errors"),m=join(e,"middlewares"),u=join(e,"routes");return {rc:n,root:r,app:e,middlewareFilePath:m,routesFilePath:u,config:{base:i,bodyParserFile:a,appConfigFile:o},controllers:{base:f},services:{base:l},errors:{base:d}}}var b=r=>{let n=["ts","mts","js","mjs","cjs","cts"];for(let e of n){let i=`${r}.${e}`;if(existsSync(i))return i}return null},R=r=>existsSync(r)?r:null;function S(r){if(!r)return "";let n=N.sep;return r.endsWith(n)?r:r+n}var I="*.{js,ts,mjs,cjs,mts,cts}",_=["!*.d.{ts,mts,mjs,cts}","!*.map"];async function C(r){let n=await glob([I,..._],{cwd:r}),e=new Set;return n.forEach(i=>{let o=i.replace(/\.(js|ts|mjs|cjs|mts|cts)$/,"");e.add(o);}),Array.from(e)}async function U(r){let{config:n}=P(r),e=n.base;if(a.debug("Loading all configurations from: `"+S(relative(r,n.base)+"`")),!R(e)){a.debug("No config directory found. Looked for:",e);return}let o=await C(e);a.debug(`Found ${o.length} config files: %s`,`
11
- ${o.join(`
12
- `)}`);for(let f of o){let l=b(join(e,f));if(!l){a.warn(`No config file found for topic: ${f}`);continue}try{let m=await import(pathToFileURL(l).href),u=m.default||m;typeof u=="function"&&(u=await u());let x=f.replace(/[-_](\w)/g,(B,h)=>h?h.toUpperCase():"");a$1[x]=u;let j=relative(r,l);a.debug(`Loaded config: \`${x}\` from \`${j}\``);}catch(d){a.error(`Failed to load config ${f}:`,d);}}}
11
+ function A(r,t,e$1){return r.listen(t,async()=>{e$1&&(a.debug("Executing onStart hook..."),await e$1().catch(i=>{a.error("Error during onStart hook:",i);})),a.box({message:`Server is running at http://localhost:${t}`,style:{borderColor:"cyan"},level:"info"});try{await e.emit("app:mounted",{app:r});}catch(i){a.error("Error during app:mounted event:",i);}finally{f();}})}function F(r,t){process.on("SIGINT",async()=>{a.info("Received SIGINT. Shutting down gracefully..."),await new Promise(e=>{r.close(async s=>s instanceof Error?(a.error("Error shutting down server:",s),e()):(t&&await t().catch(i=>{a.error("Error during shutdown hook:",i);}),a.info("Server has been shut down."),e()));}),process.exit(0);});}function T(r){return r}function $(r){return r}async function L({app:r},t){a.debug("Loading kernel...");let{kernel:e,kernel2:s,listener:i,appBootstrap:d}=t,p=s;if(e&&typeof e=="function"&&(p=e),p&&typeof p=="function")try{let n=await p(),l=typeof n=="object"&&n!==null&&"default"in n?n.default:n;typeof l=="function"?(await l({app:r}),a.debug("Middleware kernel loaded.")):a.warn("Middleware kernel setup function not found.");}catch(n){throw a.error("Error loading middleware kernel:",n),n}if(i&&typeof i=="function")try{await a$1(i);}catch(n){throw a.error("Error loading listener:",n),n}if(d&&typeof d=="function")try{await d({app:r});}catch(n){throw a.error("Error during boot process:",n),n}a.debug("Kernel loaded.");}function g(r){return Router(r)}function B(r,t){let e=g(t);return r(e),e}function b(r){let t=join(r,"expresspack.config"),e=join(r,"app"),s=join(r,"config"),i=join(s,"app"),d=join(s,"body-parser"),p=join(e,"controllers"),n=join(e,"services"),l=join(e,"errors"),u=join(e,"middlewares"),m=join(e,"routes");return {rc:t,root:r,app:e,middlewareFilePath:u,routesFilePath:m,config:{base:s,bodyParserFile:d,appConfigFile:i},controllers:{base:p},services:{base:n},errors:{base:l}}}var R=r=>{let t=["ts","mts","js","mjs","cjs","cts"];for(let e of t){let s=`${r}.${e}`;if(existsSync(s))return s}return null},k=r=>existsSync(r)?r:null;function C(r){if(!r)return "";let t=M.sep;return r.endsWith(t)?r:r+t}var D="*.{js,ts,mjs,cjs,mts,cts}",I=["!*.d.{ts,mts,mjs,cts}","!*.map"];async function S(r){let t=await glob([D,...I],{cwd:r}),e=new Set;return t.forEach(s=>{let i=s.replace(/\.(js|ts|mjs|cjs|mts|cts)$/,"");e.add(i);}),Array.from(e)}async function U(r){let{config:t}=b(r),e=t.base;if(a.debug("Loading all configurations from: `"+C(relative(r,t.base)+"`")),!k(e)){a.debug("No config directory found. Looked for:",e);return}let i=await S(e);a.debug(`Found ${i.length} config files: %s`,`
12
+ ${i.join(`
13
+ `)}`);for(let p of i){let n=R(join(e,p));if(!n){a.warn(`No config file found for topic: ${p}`);continue}try{let u=await import(pathToFileURL(n).href),m=u.default||u;typeof m=="function"&&(m=await m());let x=p.replace(/[-_](\w)/g,(H,y)=>y?y.toUpperCase():"");a$2[x]=m;let j=relative(r,n);a.debug(`Loaded config: \`${x}\` from \`${j}\``);}catch(l){a.error(`Failed to load config ${p}:`,l);}}}
13
14
 
14
- export { U as configLoader, g as createRouter, L as defineKernel, K as defineRouterMiddleware, T as gracefulHTTPStart, k as gracefulShutdown, $ as loadKernel };
15
+ export { U as configLoader, g as createRouter, T as defineKernel, $ as defineMiddlewareKernel, B as defineRouterMiddleware, A as gracefulHTTPStart, F as gracefulShutdown, L as loadKernel };
@@ -0,0 +1,48 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ /**
4
+ * Configuration options for context middleware
5
+ */
6
+ interface ContextStoreConfig {
7
+ /**
8
+ * Whether to enable the context middleware
9
+ * @default true
10
+ */
11
+ enabled?: boolean;
12
+ }
13
+ /**
14
+ * Express middleware that initializes async context for each request
15
+ * This middleware must be registered before any code that uses getAppContext()
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import express from 'express';
20
+ * import { contextStoreMiddleware } from 'expresspack';
21
+ *
22
+ * const app = express();
23
+ *
24
+ * // Register as early as possible
25
+ * app.use(contextStoreMiddleware());
26
+ * ```
27
+ */
28
+ declare function contextStoreMiddleware(): (req: Request, res: Response, next: NextFunction) => void;
29
+ /**
30
+ * For types you need to augment the Request type to include appContext
31
+ * and also include the type for appContext.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * declare global {
36
+ * namespace Express {
37
+ * interface Request {
38
+ * appContext: {
39
+ * user: User;
40
+ * session: Session;
41
+ * };
42
+ * }
43
+ * }
44
+ * ```
45
+ */
46
+ declare function simpleContextMiddleware(): (req: Request, res: Response, next: NextFunction) => void;
47
+
48
+ export { type ContextStoreConfig, contextStoreMiddleware, simpleContextMiddleware };
@@ -0,0 +1,6 @@
1
+ import { a } from '../../chunk-55RBYZEZ.mjs';
2
+ import { a as a$1 } from '../../chunk-FFCH7NYQ.mjs';
3
+
4
+ function u(){return (e,p,t)=>{let n={data:new Map};a.run(n,()=>{t();});}}function c(){return (e,p,t)=>{let n=a$1(e);e.appContext=n,t();}}
5
+
6
+ export { u as contextStoreMiddleware, c as simpleContextMiddleware };
@@ -1,7 +1,7 @@
1
- import express, { Handler } from 'express';
1
+ import express__default, { Handler } from 'express';
2
2
 
3
- type JSONOptions = Parameters<typeof express.json>[0];
4
- type URLEncodedOptions = Parameters<typeof express.urlencoded>[0];
3
+ type JSONOptions = Parameters<typeof express__default.json>[0];
4
+ type URLEncodedOptions = Parameters<typeof express__default.urlencoded>[0];
5
5
  type BodyParserConfig = {
6
6
  json?: JSONOptions;
7
7
  urlencoded?: URLEncodedOptions;
@@ -1,20 +1,36 @@
1
1
  import * as Emittery from 'emittery';
2
2
  import Emittery__default from 'emittery';
3
3
  export { default as Emittery } from 'emittery';
4
+ import * as express from 'express';
4
5
 
5
6
  /**
6
7
  * Base event map that users can extend in their applications
7
8
  */
8
9
  interface EmitterEvents {
9
- 'app:mounted': undefined;
10
+ "app:mounted": {
11
+ app: express.Express;
12
+ };
10
13
  }
11
14
  /**
12
15
  * Default emitter instance for convenient access
13
16
  */
14
- declare const emitter: Emittery__default<EmitterEvents, EmitterEvents & Emittery.OmnipresentEventData, "app:mounted">;
17
+ declare const emitter: Emittery__default<EmitterEvents, EmitterEvents & Emittery.OmnipresentEventData, never>;
15
18
  /**
16
19
  * Create a new emitter instance (for testing or isolated use)
17
20
  */
18
21
  declare function createEmitter<T extends EmitterEvents = EmitterEvents>(): Emittery__default<T>;
22
+ type EventHandler<K extends keyof EmitterEvents> = (payload?: EmitterEvents[K]) => void | Promise<void>;
23
+ type RegisterEventCallback = <K extends keyof EmitterEvents>(event: K, handler: EventHandler<K> | (() => Promise<EventHandler<K>> | Promise<{
24
+ default: any;
25
+ }>)) => void;
26
+ interface DefineEventContext {
27
+ /**
28
+ * Syntactic sugar for registering event listeners
29
+ */
30
+ on: RegisterEventCallback;
31
+ emitter: typeof emitter;
32
+ }
33
+ declare function defineEvents(setup: (context: DefineEventContext) => void): void;
34
+ declare function defineEventHandler<K extends keyof EmitterEvents>(event: K, handler: EventHandler<K> | (() => Promise<EventHandler<K>>)): EventHandler<K> | (() => Promise<EventHandler<K>>);
19
35
 
20
- export { type EmitterEvents, createEmitter, emitter as default, emitter };
36
+ export { type DefineEventContext, type EmitterEvents, type EventHandler, type RegisterEventCallback, createEmitter, emitter as default, defineEventHandler, defineEvents, emitter };
@@ -1 +1 @@
1
- export { b as createEmitter, c as default, a as emitter } from '../../chunk-CRIPGIHI.mjs';
1
+ export { b as createEmitter, e as default, d as defineEventHandler, c as defineEvents, a as emitter } from '../../chunk-OXUMMLIO.mjs';
@@ -1,6 +1,6 @@
1
- import n from 'consola';
1
+ import r from 'consola';
2
2
  import { env } from 'process';
3
3
 
4
- var e=env.APP_LOG_LEVEL,l=n.create({level:Number.isNaN(Number(e))?3:Number(e)});function s(o){return l.withTag(o)}function u(o,r){return n.create({level:r.level??(Number.isNaN(Number(e))?3:Number(e))}).withTag(o)}var m=s;
4
+ var s=r.create({level:Number.isNaN(Number(env.APP_LOG_LEVEL))?3:Number(env.APP_LOG_LEVEL)});function l(e){return s.withTag(e)}function p(e,t){let o=process.env.APP_LOG_LEVEL;return r.create({level:t.level??(Number.isNaN(Number(o))?3:Number(o))}).withTag(e)}var u=l;
5
5
 
6
- export { m as Logger, u as createConsoleLogger, l as println, s as useConsoleLogger };
6
+ export { u as Logger, p as createConsoleLogger, s as println, l as useConsoleLogger };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Dynamically import a module and ensure it has a default export
3
+ */
4
+ declare function importDefault<T extends object>(importFn: () => Promise<T>, filePath?: string): Promise<T extends {
5
+ default: infer A;
6
+ } ? A : never>;
7
+
8
+ export { importDefault };
@@ -0,0 +1 @@
1
+ export { a as importDefault } from '../chunk-JKH5TYED.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kuwan-expresspack-core",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -33,6 +33,10 @@
33
33
  "types": "./dist/env.d.ts",
34
34
  "import": "./dist/env.mjs"
35
35
  },
36
+ "./env-config": {
37
+ "types": "./dist/env-config.d.ts",
38
+ "import": "./dist/env-config.mjs"
39
+ },
36
40
  "./config": {
37
41
  "types": "./dist/config.d.ts",
38
42
  "import": "./dist/config.mjs"
@@ -53,6 +57,18 @@
53
57
  "types": "./dist/middlewares/error-handler/index.d.ts",
54
58
  "import": "./dist/middlewares/error-handler/index.mjs"
55
59
  },
60
+ "./middlewares/app-context": {
61
+ "types": "./dist/middlewares/app-context/index.d.ts",
62
+ "import": "./dist/middlewares/app-context/index.mjs"
63
+ },
64
+ "./context-store": {
65
+ "types": "./dist/context/context-store/index.d.ts",
66
+ "import": "./dist/context/context-store/index.mjs"
67
+ },
68
+ "./simple-context": {
69
+ "types": "./dist/context/simple-context.d.ts",
70
+ "import": "./dist/context/simple-context.mjs"
71
+ },
56
72
  "./services/*": {
57
73
  "types": "./dist/services/*/index.d.ts",
58
74
  "import": "./dist/services/*/index.mjs"
@@ -1,12 +0,0 @@
1
- import { z } from 'zod';
2
- import { config } from '@dotenvx/dotenvx';
3
- import O from 'consola';
4
- import { colorize } from 'consola/utils';
5
-
6
- var v=process.env.EXPRESSPACK_LOG_LEVEL,h=O.create({level:Number.isNaN(Number(v))?3:Number(v)});function E(r){switch(typeof r){case "number":case "bigint":return colorize("cyan",r.toString());case "boolean":return colorize(r?"green":"red",String(r));case "symbol":return colorize("magenta",r.toString());case "string":return isNaN(Number(r))?colorize("whiteBright",`${r}`):colorize("yellow",`'${r}'`);case "undefined":return colorize("gray","undefined")}return r===null?colorize("dim","null"):String(r)}var o=h;var f,s=null,c=null,m={};function w(r,e){let t=r.safeParse(e);if(t.success)return t.data;console.error("\u274C Invalid environment variables:"),console.error(z.prettifyError(t.error));}function C(r,e,t={fatal:false,immediate_log_error:true,log_error_after_graceful_start:true}){if(m=t,t.fatal)try{let n=r.parse(e);return {...f,...n}}catch(n){throw n instanceof z.ZodError?(s=z.prettifyError(n),c=n,o.error("\u274C Invalid environment variables:"),o.error("\u274C",s),new Error("Invalid environment variables. The environment variable did not pass the schema validation. Check if you have set all required environment variables correctly.")):n}let i=r.safeParse(e);if(!i.success){let n=r.partial().safeParse(e);if(!n.success)return s=z.prettifyError(i.error),c=i.error,t.immediate_log_error&&(o.error("\u274C Invalid environment variables:"),o.error("\u274C",s)),f||{};s=z.prettifyError(i.error),c=i.error,t.immediate_log_error&&(o.error("\u274C Invalid environment variables:"),o.error("\u274C",s));let d=r.keyof();for(let g of d.options)g in n.data||(n.data[g]=void 0);return {...f,...n.data}}return {...f,...i.data}}function N(){return c}function b(){return s}function P(r){if(!r||Object.keys(r).length===0){o.warn("No environment variables to print. Make sure the env is complete and valid.");return}let e=Object.entries(r).sort(([l],[p])=>l.localeCompare(p)),t=Math.max(...e.map(([l])=>l.length))+2,i=e.map(([l,p])=>`${l.padEnd(t," ")} ${E(p)}`),n=`KEY${" ".repeat(t-3)} VALUE`,d=" ".repeat(n.length);return [d,n,d,...i].join(`
7
- `)}function S(){if(m){let{log_error_after_graceful_start:r}=m;if(r){let e=b();e&&o.error("Invalid Environment Variable Value",`
8
- -----
9
- ${e}
10
- -----`);}}}function k(r){let e=config(r);return f=e.parsed?e.parsed:void 0,e}var Z={create:C,parseEnv:w,prettifyEnv:P,getEnvErrorRaw:N,getEnvErrorString:b,logEnvErrors:S,config:k};
11
-
12
- export { o as a, C as b, N as c, b as d, P as e, S as f, k as g, Z as h };
@@ -1,6 +0,0 @@
1
- import t from 'emittery';
2
- import { env } from 'process';
3
-
4
- function E(){return env.EXPRESSPACK_EVENT_EMITTER_DEBUG==="true"||env.EXPRESSPACK_EVENT_EMITTER_DEBUG==="1"||(typeof env.EXPRESSPACK_EVENT_EMITTER_DEBUG=="boolean"?env.EXPRESSPACK_EVENT_EMITTER_DEBUG===true:false)}var r=new t({debug:{name:"expresspack-emitter",enabled:E()}});function T(){return new t({debug:{name:"c-emitter",enabled:E()}})}var a=r;
5
-
6
- export { r as a, T as b, a as c };