kuwan-expresspack-core 0.1.16 → 0.1.18

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,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,13 @@
1
+ import { z } from 'zod';
2
+ import { config } from '@dotenvx/dotenvx';
3
+ import { colorize } from 'consola/utils';
4
+ import w 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=w.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 d,c=null,v=null,y={},E=[];function I(r,n){let t=r.safeParse(n);if(t.success)return t.data;console.error("\u274C Invalid environment variables:"),console.error(z.prettifyError(t.error));}function R(r,n,t={fatal:false,immediate_log_error:true,log_error_after_graceful_start:true}){if(b(),y=t,t.fatal)try{let o=r.parse(n);return {...d,...o}}catch(o){throw o instanceof z.ZodError?(c=z.prettifyError(o),v=o,s.error("\u274C Invalid environment variables:"),s.error("\u274C",c),new Error("Invalid environment variables. The environment variable did not pass the schema validation. Check if you have set all required environment variables correctly.")):o}let i=r.safeParse(n);if(!i.success){let o=r.partial().safeParse(n);if(!o.success)return c=z.prettifyError(i.error),v=i.error,t.immediate_log_error&&(s.error("\u274C Invalid environment variables:"),s.error("\u274C",c)),d||{};c=z.prettifyError(i.error),v=i.error,t.immediate_log_error&&(s.error("\u274C Invalid environment variables:"),s.error("\u274C",c));let f=r.keyof();E=f.options;for(let p of f.options)p in o.data||(o.data[p]=void 0);return {...d,...o.data}}let a=r.keyof();E=a.options;for(let o of a.options)o in i.data||(i.data[o]=void 0);return {...d,...i.data}}function T(){return v}function S(){return c}function L(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,t=e=>E.includes(e)?e:`* ${e}`,i=e=>e.startsWith("! ")?m("dim",m("yellow",`${e}`)):e,a=e=>E.includes(e)&&r[e]===void 0?`! ${e}`:e,o=Object.entries(r).sort(([e],[l])=>e.localeCompare(l)).map(([e,l])=>[t(e),l]).map(([e,l])=>[a(e),l]),f=Math.max(...o.map(([e])=>e.length))+2,p=o.map(([e,l])=>`${e.padEnd(f," ").replace(e,n(e)).replace(e,i(e))} ${N(l)}`),_=`KEY${" ".repeat(f-3)} VALUE`,h=" ".repeat(_.length);return [h,_,h,...p].join(`
7
+ `)}function $(){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,n){s.log("[Environment Variables] on `env.ts`");let t=Object.fromEntries(Object.entries({...r}).map(([i,a])=>typeof a=="string"&&a.length>36?[i,`${a.slice(0,36)}...`]:n?n(i,a):[i,a]));s.log(`${L(t)}
11
+ `);}function C(r){d={};let n=config(r);return b(),d=n.parsed?n.parsed:void 0,n}function K(r){return new Proxy(r,{get(n,t){return t in n?n[t]:process.env[t]}})}function j(r,n,t){let i=R(r,n,t);return K(i)}var H={create:j,parseEnv:I,prettifyEnv:L,getEnvErrorRaw:T,getEnvErrorString:S,logEnvErrors:$,config:C};
12
+
13
+ export { s as a, R as b, T as c, S as d, L as e, $ as f, k as g, C as h, H as i };
@@ -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';
@@ -1,3 +1,3 @@
1
- import { g } from './chunk-CZGPAGDK.mjs';
1
+ import { h } from './chunk-XWAHBJNF.mjs';
2
2
 
3
- g();
3
+ h();
package/dist/env.d.ts CHANGED
@@ -55,6 +55,13 @@ declare function prettifyEnv(env: Record<string, any>): string | undefined;
55
55
  * Errors are already logged after by graceful start.
56
56
  */
57
57
  declare function logEnvErrors(): void;
58
+ /**
59
+ * This will print the passed env vars regardless of the NODE_ENV,
60
+ * it is on your discretion on when to call this function.
61
+ *
62
+ * @param envVars The environment variables to log
63
+ */
64
+ declare function debugEnvVars(envVars: Record<string, any>, redactFunction?: (key: string, value: any) => [string, any]): void;
58
65
  declare function config(options?: DotenvConfigOptions | undefined): DotenvConfigOutput;
59
66
  declare function createProxy<T extends z.ZodObject<any>>(schema: T, data: unknown, options?: Partial<EnvOptions>): z.output<T>;
60
67
  declare const _default: {
@@ -67,4 +74,4 @@ declare const _default: {
67
74
  config: typeof config;
68
75
  };
69
76
 
70
- export { type EnvOptions, config, create, _default as default, getEnvErrorRaw, getEnvErrorString, logEnvErrors, prettifyEnv };
77
+ export { type EnvOptions, config, create, debugEnvVars, _default as default, getEnvErrorRaw, getEnvErrorString, logEnvErrors, prettifyEnv };
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-CZGPAGDK.mjs';
1
+ export { h as config, b as create, g as debugEnvVars, i as default, c as getEnvErrorRaw, d as getEnvErrorString, f as logEnvErrors, e as prettifyEnv } from './chunk-XWAHBJNF.mjs';
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { a as a$1 } from './chunk-JKH5TYED.mjs';
2
1
  import { e } from './chunk-OXUMMLIO.mjs';
2
+ import { a as a$1 } from './chunk-JKH5TYED.mjs';
3
3
  import { a as a$2 } from './chunk-VSPZT4K6.mjs';
4
- import { a, f } from './chunk-CZGPAGDK.mjs';
4
+ import { a, f } from './chunk-XWAHBJNF.mjs';
5
5
  import { Router } from 'express';
6
6
  import M, { relative, join } from 'path';
7
7
  import { existsSync } from 'fs';
@@ -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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kuwan-expresspack-core",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -57,6 +57,18 @@
57
57
  "types": "./dist/middlewares/error-handler/index.d.ts",
58
58
  "import": "./dist/middlewares/error-handler/index.mjs"
59
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
+ },
60
72
  "./services/*": {
61
73
  "types": "./dist/services/*/index.d.ts",
62
74
  "import": "./dist/services/*/index.mjs"
@@ -1,12 +0,0 @@
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 };