@modelence/react-query 1.2.2 → 1.2.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.
- package/.yalc/modelence/dist/bin/modelence.js +2 -2
- package/.yalc/modelence/dist/bin/modelence.js.map +1 -1
- package/.yalc/modelence/dist/chunk-KTGXKFME.js +3 -0
- package/.yalc/modelence/dist/chunk-KTGXKFME.js.map +1 -0
- package/.yalc/modelence/dist/chunk-PB6WQQ4L.js +3 -0
- package/.yalc/modelence/dist/chunk-PB6WQQ4L.js.map +1 -0
- package/.yalc/modelence/dist/client.d.ts +1 -1
- package/.yalc/modelence/dist/client.js +1 -1
- package/.yalc/modelence/dist/client.js.map +1 -1
- package/.yalc/modelence/dist/index.d.ts +1 -1
- package/.yalc/modelence/dist/{package-3YQBVIVQ.js → package-46B3WEOU.js} +2 -2
- package/.yalc/modelence/dist/{package-3YQBVIVQ.js.map → package-46B3WEOU.js.map} +1 -1
- package/.yalc/modelence/dist/server.d.ts +60 -30
- package/.yalc/modelence/dist/server.js +7 -7
- package/.yalc/modelence/dist/server.js.map +1 -1
- package/.yalc/modelence/dist/telemetry.js +1 -1
- package/.yalc/modelence/dist/{types-Ds1ESQSs.d.ts → types-BOFsm7A2.d.ts} +50 -1
- package/.yalc/modelence/dist/{types-WgRbQ-tj.d.ts → types-V9eDnP35.d.ts} +41 -40
- package/.yalc/modelence/dist/types.d.ts +3 -3
- package/.yalc/modelence/package.json +5 -2
- package/.yalc/modelence/yalc.sig +1 -1
- package/package.json +2 -2
- package/yalc.lock +2 -2
- package/.yalc/modelence/dist/chunk-3YAV3UUU.js +0 -3
- package/.yalc/modelence/dist/chunk-3YAV3UUU.js.map +0 -1
- package/.yalc/modelence/dist/chunk-DVECB2TP.js +0 -3
- package/.yalc/modelence/dist/chunk-DVECB2TP.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{l as captureError,h as logDebug,j as logError,i as logInfo,k as startTransaction}from'./chunk-
|
|
1
|
+
export{l as captureError,h as logDebug,j as logError,i as logInfo,k as startTransaction}from'./chunk-PB6WQQ4L.js';//# sourceMappingURL=telemetry.js.map
|
|
2
2
|
//# sourceMappingURL=telemetry.js.map
|
|
@@ -39,6 +39,55 @@ type RoleDefinition = {
|
|
|
39
39
|
description?: string;
|
|
40
40
|
permissions: Permission[];
|
|
41
41
|
};
|
|
42
|
+
type AuthProvider = 'google' | 'github' | 'email';
|
|
43
|
+
type AuthSuccessProps = {
|
|
44
|
+
provider: AuthProvider;
|
|
45
|
+
user: User;
|
|
46
|
+
session: Session | null;
|
|
47
|
+
connectionInfo: ConnectionInfo;
|
|
48
|
+
};
|
|
49
|
+
type AuthErrorProps = {
|
|
50
|
+
provider: AuthProvider;
|
|
51
|
+
error: Error;
|
|
52
|
+
session: Session | null;
|
|
53
|
+
connectionInfo: ConnectionInfo;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
type ClientInfo = {
|
|
57
|
+
screenWidth: number;
|
|
58
|
+
screenHeight: number;
|
|
59
|
+
windowWidth: number;
|
|
60
|
+
windowHeight: number;
|
|
61
|
+
pixelRatio: number;
|
|
62
|
+
orientation: string | null;
|
|
63
|
+
};
|
|
64
|
+
type ConnectionInfo = {
|
|
65
|
+
ip?: string;
|
|
66
|
+
userAgent?: string;
|
|
67
|
+
acceptLanguage?: string;
|
|
68
|
+
referrer?: string;
|
|
69
|
+
baseUrl?: string;
|
|
70
|
+
};
|
|
71
|
+
type Context = {
|
|
72
|
+
session: Session | null;
|
|
73
|
+
user: UserInfo | null;
|
|
74
|
+
roles: string[];
|
|
75
|
+
clientInfo: ClientInfo;
|
|
76
|
+
connectionInfo: ConnectionInfo;
|
|
77
|
+
};
|
|
78
|
+
type Args = Record<string, unknown>;
|
|
79
|
+
type Handler<T = unknown> = (args: Args, context: Context) => Promise<T> | T;
|
|
80
|
+
type MethodType = 'query' | 'mutation';
|
|
81
|
+
type MethodDefinition<T = unknown> = {
|
|
82
|
+
permissions?: Permission[];
|
|
83
|
+
handler: Handler<T>;
|
|
84
|
+
} | Handler<T>;
|
|
85
|
+
type Method<T = unknown> = {
|
|
86
|
+
type: MethodType;
|
|
87
|
+
name: string;
|
|
88
|
+
permissions: Permission[];
|
|
89
|
+
handler: Handler<T>;
|
|
90
|
+
};
|
|
42
91
|
|
|
43
92
|
type canAccessChannel = (props: {
|
|
44
93
|
user: User | null;
|
|
@@ -103,4 +152,4 @@ interface WebsocketClientProvider {
|
|
|
103
152
|
}): void;
|
|
104
153
|
}
|
|
105
154
|
|
|
106
|
-
export { type
|
|
155
|
+
export { type AuthSuccessProps as A, type ConfigSchema as C, type DefaultRoles as D, type Handler as H, type MethodDefinition as M, type Permission as P, type RoleDefinition as R, ServerChannel as S, type User as U, type WebsocketServerProvider as W, type WebsocketClientProvider as a, type ConfigKey as b, ClientChannel as c, type AuthErrorProps as d, type AppConfig as e, type Session as f, type UserInfo as g, type Role as h, type Context as i, type ClientInfo as j, type ConnectionInfo as k, type Args as l, type MethodType as m, type Method as n, type ConfigType as o, type Configs as p, type AuthProvider as q };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import './index-CwdohC5n.js';
|
|
2
|
-
import {
|
|
2
|
+
import { i as Context } from './types-BOFsm7A2.js';
|
|
3
3
|
import * as mongodb from 'mongodb';
|
|
4
4
|
import { WithId, IndexDescription, SearchIndexDescription, MongoClient, Collection, FilterOperators, Document, FindOptions, ObjectId, OptionalUnlessRequiredId, InsertOneResult, InsertManyResult, UpdateFilter, UpdateResult, ClientSession, DeleteResult, AggregateOptions, AggregationCursor, AnyBulkWriteOperation, BulkWriteResult } from 'mongodb';
|
|
5
5
|
import { z, ZodNumber, ZodArray } from 'zod';
|
|
@@ -30,42 +30,6 @@ interface EmailProvider {
|
|
|
30
30
|
sendEmail(data: EmailPayload): Promise<void>;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
type ClientInfo = {
|
|
34
|
-
screenWidth: number;
|
|
35
|
-
screenHeight: number;
|
|
36
|
-
windowWidth: number;
|
|
37
|
-
windowHeight: number;
|
|
38
|
-
pixelRatio: number;
|
|
39
|
-
orientation: string | null;
|
|
40
|
-
};
|
|
41
|
-
type ConnectionInfo = {
|
|
42
|
-
ip?: string;
|
|
43
|
-
userAgent?: string;
|
|
44
|
-
acceptLanguage?: string;
|
|
45
|
-
referrer?: string;
|
|
46
|
-
baseUrl?: string;
|
|
47
|
-
};
|
|
48
|
-
type Context = {
|
|
49
|
-
session: Session | null;
|
|
50
|
-
user: UserInfo | null;
|
|
51
|
-
roles: string[];
|
|
52
|
-
clientInfo: ClientInfo;
|
|
53
|
-
connectionInfo: ConnectionInfo;
|
|
54
|
-
};
|
|
55
|
-
type Args = Record<string, unknown>;
|
|
56
|
-
type Handler<T = unknown> = (args: Args, context: Context) => Promise<T> | T;
|
|
57
|
-
type MethodType = 'query' | 'mutation';
|
|
58
|
-
type MethodDefinition<T = unknown> = {
|
|
59
|
-
permissions?: Permission[];
|
|
60
|
-
handler: Handler<T>;
|
|
61
|
-
} | Handler<T>;
|
|
62
|
-
type Method<T = unknown> = {
|
|
63
|
-
type: MethodType;
|
|
64
|
-
name: string;
|
|
65
|
-
permissions: Permission[];
|
|
66
|
-
handler: Handler<T>;
|
|
67
|
-
};
|
|
68
|
-
|
|
69
33
|
type RateLimitType = 'ip' | 'user';
|
|
70
34
|
type RateLimitRule = {
|
|
71
35
|
/** Logical action being limited, e.g. "signup" */
|
|
@@ -158,6 +122,38 @@ type StrictRootFilterOperators<TSchema> = {
|
|
|
158
122
|
$expr?: any;
|
|
159
123
|
$jsonSchema?: any;
|
|
160
124
|
};
|
|
125
|
+
/**
|
|
126
|
+
* Helper type to extract array element type
|
|
127
|
+
* @internal
|
|
128
|
+
*/
|
|
129
|
+
type ArrayElement<T> = T extends (infer E)[] ? E : never;
|
|
130
|
+
/**
|
|
131
|
+
* Helper type for $in/$nin that accepts any array/tuple where elements are assignable to T
|
|
132
|
+
* This solves the issue where TypeScript infers ['a', 'b'] as a tuple instead of ('a' | 'b')[]
|
|
133
|
+
* and where Array<Union> gets distributed into Union1[] | Union2[] | ...
|
|
134
|
+
* We wrap the Exclude in a tuple check to prevent distribution
|
|
135
|
+
* @internal
|
|
136
|
+
*/
|
|
137
|
+
type NonUndefined<T> = T extends undefined ? never : T;
|
|
138
|
+
type ArrayLikeOfUnion<T> = [NonUndefined<T>] extends [never] ? never : ReadonlyArray<NonUndefined<T>> | Array<NonUndefined<T>>;
|
|
139
|
+
/**
|
|
140
|
+
* Enhanced FilterOperators that fixes $in and $nin to properly accept arrays of union types
|
|
141
|
+
* MongoDB's native FilterOperators has issues with union types in $in/$nin arrays
|
|
142
|
+
* because TypeScript distributes Array<Union> into Array1 | Array2 | ...
|
|
143
|
+
* @internal
|
|
144
|
+
*/
|
|
145
|
+
type EnhancedFilterOperators<T> = Omit<FilterOperators<T>, '$in' | '$nin'> & {
|
|
146
|
+
$in?: ArrayLikeOfUnion<T>;
|
|
147
|
+
$nin?: ArrayLikeOfUnion<T>;
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Custom filter value type that handles array fields specially:
|
|
151
|
+
* - For array fields: allows element type, full array type, or FilterOperators
|
|
152
|
+
* - For non-array fields: allows exact type or FilterOperators
|
|
153
|
+
* We use [T] to prevent distribution when T is a union type
|
|
154
|
+
* @internal
|
|
155
|
+
*/
|
|
156
|
+
type FilterValue<T> = [T] extends [unknown[]] ? ArrayElement<T> | T | EnhancedFilterOperators<T> : [T] extends [never] ? never : T | EnhancedFilterOperators<[T] extends [never] ? never : T>;
|
|
161
157
|
/**
|
|
162
158
|
* Type-safe MongoDB filter that ensures only schema fields can be queried
|
|
163
159
|
* while supporting all MongoDB query operators and dot notation for nested fields.
|
|
@@ -165,6 +161,7 @@ type StrictRootFilterOperators<TSchema> = {
|
|
|
165
161
|
* This type combines:
|
|
166
162
|
* - MongoDB's native `FilterOperators<T>` for field-level operators (comprehensive operator support)
|
|
167
163
|
* - Custom `StrictRootFilterOperators<T>` for top-level operators without index signature
|
|
164
|
+
* - Custom array field handling: allows passing single element when field is an array
|
|
168
165
|
* - Custom restriction: only strings containing dots are allowed for nested field queries
|
|
169
166
|
*
|
|
170
167
|
* @example
|
|
@@ -174,6 +171,7 @@ type StrictRootFilterOperators<TSchema> = {
|
|
|
174
171
|
* name: schema.string(),
|
|
175
172
|
* age: schema.number(),
|
|
176
173
|
* tags: schema.array(schema.string()),
|
|
174
|
+
* collections: schema.array(schema.string()),
|
|
177
175
|
* address: schema.object({
|
|
178
176
|
* street: schema.string(),
|
|
179
177
|
* city: schema.string(),
|
|
@@ -190,6 +188,9 @@ type StrictRootFilterOperators<TSchema> = {
|
|
|
190
188
|
* await dbUsers.findOne({ tags: { $in: ['typescript', 'mongodb'] } });
|
|
191
189
|
* await dbUsers.findOne({ $or: [{ name: 'John' }, { name: 'Jane' }] });
|
|
192
190
|
*
|
|
191
|
+
* // ✅ Valid - array field with single element (checks if array contains the element)
|
|
192
|
+
* await dbUsers.findOne({ collections: 'users' });
|
|
193
|
+
*
|
|
193
194
|
* // ✅ Valid - dot notation for nested fields (must contain a dot)
|
|
194
195
|
* await dbUsers.findOne({ 'address.city': 'New York' });
|
|
195
196
|
* await dbUsers.findOne({ 'emails.0.address': 'test@example.com' });
|
|
@@ -199,9 +200,9 @@ type StrictRootFilterOperators<TSchema> = {
|
|
|
199
200
|
* ```
|
|
200
201
|
*/
|
|
201
202
|
type TypedFilter<T> = {
|
|
202
|
-
[K in keyof WithId<T>]?:
|
|
203
|
+
[K in keyof WithId<T>]?: FilterValue<WithId<T>[K]>;
|
|
203
204
|
} & StrictRootFilterOperators<T> & {
|
|
204
|
-
[K:
|
|
205
|
+
[K: `${string}.${string}`]: any;
|
|
205
206
|
};
|
|
206
207
|
/**
|
|
207
208
|
* Helper type to preserve method types when extending a store.
|
|
@@ -642,4 +643,4 @@ type RouteDefinition = {
|
|
|
642
643
|
};
|
|
643
644
|
type ExpressHandler = (req: Request, res: Response) => Promise<void> | void;
|
|
644
645
|
|
|
645
|
-
export { type
|
|
646
|
+
export { type BodyConfig as B, type CronJobInputParams as C, type EmailProvider as E, type HttpMethod as H, type InferDocumentType as I, type ModelSchema as M, type RouteDefinition as R, Store as S, type RateLimitRule as a, type RateLimitType as b, type EmailPayload as c, type RouteHandler as d, type RouteParams as e, type RouteResponse as f, type EmailAttachment as g, type CronJob as h, type CronJobMetadata as i, type RouteHandlers as j, type ExpressHandler as k, schema as s };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { A as AppServer, E as ExpressMiddleware, M as ModelenceConfig } from './index-CwdohC5n.js';
|
|
2
|
-
export {
|
|
3
|
-
export {
|
|
2
|
+
export { e as AppConfig, l as Args, d as AuthErrorProps, q as AuthProvider, A as AuthSuccessProps, j as ClientInfo, b as ConfigKey, C as ConfigSchema, o as ConfigType, p as Configs, k as ConnectionInfo, i as Context, D as DefaultRoles, H as Handler, n as Method, M as MethodDefinition, m as MethodType, P as Permission, h as Role, R as RoleDefinition, f as Session, U as User, g as UserInfo, a as WebsocketClientProvider, W as WebsocketServerProvider } from './types-BOFsm7A2.js';
|
|
3
|
+
export { B as BodyConfig, h as CronJob, C as CronJobInputParams, i as CronJobMetadata, g as EmailAttachment, c as EmailPayload, E as EmailProvider, k as ExpressHandler, H as HttpMethod, I as InferDocumentType, M as ModelSchema, a as RateLimitRule, b as RateLimitType, R as RouteDefinition, d as RouteHandler, j as RouteHandlers, e as RouteParams, f as RouteResponse, s as schema } from './types-V9eDnP35.js';
|
|
4
4
|
import 'express';
|
|
5
|
+
import 'http';
|
|
5
6
|
import 'mongodb';
|
|
6
7
|
import 'zod';
|
|
7
|
-
import 'http';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "modelence",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.10.2",
|
|
5
5
|
"description": "The Node.js Framework for Real-Time MongoDB Apps",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/global.d.ts",
|
|
@@ -36,6 +36,9 @@
|
|
|
36
36
|
"test:coverage": "NODE_OPTIONS=--experimental-vm-modules jest --coverage",
|
|
37
37
|
"postversion": "git push && git push --tags"
|
|
38
38
|
},
|
|
39
|
+
"lint-staged": {
|
|
40
|
+
"src/**/*.{ts,tsx,js,jsx,json,css,md}": "prettier --write"
|
|
41
|
+
},
|
|
39
42
|
"repository": {
|
|
40
43
|
"type": "git",
|
|
41
44
|
"url": "git+https://github.com/modelence/modelence.git"
|
|
@@ -76,5 +79,5 @@
|
|
|
76
79
|
"react": ">=18.0.0",
|
|
77
80
|
"react-dom": ">=18.0.0"
|
|
78
81
|
},
|
|
79
|
-
"yalcSig": "
|
|
82
|
+
"yalcSig": "6bbcd69c56a64a7a7b728f8d68fbe634"
|
|
80
83
|
}
|
package/.yalc/modelence/yalc.sig
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
6bbcd69c56a64a7a7b728f8d68fbe634
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@modelence/react-query",
|
|
4
|
-
"version": "1.2.
|
|
4
|
+
"version": "1.2.3",
|
|
5
5
|
"description": "React Query utilities for Modelence",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@tanstack/react-query": "^5.76.2",
|
|
28
28
|
"@types/react": "^19.0.0",
|
|
29
|
-
"modelence": "^0.10.
|
|
29
|
+
"modelence": "^0.10.3",
|
|
30
30
|
"react": "^19.0.0",
|
|
31
31
|
"tsup": "^8.3.6",
|
|
32
32
|
"typescript": "^5.7.2"
|
package/yalc.lock
CHANGED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var s="module",i="modelence",o="0.8.0",r="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",p="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",test:"NODE_OPTIONS=--experimental-vm-modules jest","test:watch":"NODE_OPTIONS=--experimental-vm-modules jest --watch","test:coverage":"NODE_OPTIONS=--experimental-vm-modules jest --coverage",postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",j={url:"https://github.com/modelence/modelence/issues"},g="https://modelence.com",h={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/jest":"^30.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",jest:"^30.2.0",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-jest":"^29.4.5","ts-node":"^10.9.2"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},v={react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:o,description:r,main:n,types:p,exports:c,files:d,bin:l,scripts:m,repository:a,author:y,license:u,bugs:j,homepage:g,devDependencies:h,dependencies:x,peerDependencies:v};
|
|
2
|
-
export{s as a,i as b,o as c,r as d,n as e,p as f,c as g,d as h,l as i,m as j,a as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-3YAV3UUU.js.map
|
|
3
|
-
//# sourceMappingURL=chunk-3YAV3UUU.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,QACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,eACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CACR,aAAc,2BAAA,CACd,cAAA,CAAkB,eAAA,CAClB,IAAA,CAAQ,6CAAA,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uBAAA,CAAyB,SAAA,CACzB,GAAA,CAAO,UACP,OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,CAAA,CAlGFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,EACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,KAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAWA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAaA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAqBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-3YAV3UUU.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.8.0\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"NODE_OPTIONS=--experimental-vm-modules jest\",\n \"test:watch\": \"NODE_OPTIONS=--experimental-vm-modules jest --watch\",\n \"test:coverage\": \"NODE_OPTIONS=--experimental-vm-modules jest --coverage\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"jest\": \"^30.2.0\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-jest\": \"^29.4.5\",\n \"ts-node\": \"^10.9.2\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import B from'elastic-apm-node';import v from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import c from'process';var m={},E={},w=false;function f(t){return E[t]?.value}function U(){if(!w)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(m).filter(([t,e])=>e.isPublic).map(([t,e])=>[t,{key:t,type:e.type,value:E[t]?.value??e.default}]))}function G(t){t.forEach(({key:e,type:o,value:r})=>{!e.toLowerCase().startsWith("_system.")&&!m[e]||(E[e]={key:e,type:o,value:r});}),w=true;}function V(t){Object.entries(t).forEach(([e,o])=>{let{type:r,isPublic:n}=o;if(r==="secret"&&n)throw new Error(`Config ${e} with type "secret" cannot be public`)}),m=t;}var i={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function h({elasticCloudId:t,elasticApiKey:e}){let o=c.stdout.write,r=c.stderr.write;c.stdout.write=function(n,...s){return x(n.toString(),i.stdout),o.call(c.stdout,n,...s)},c.stderr.write=function(n,...s){return x(n.toString(),i.stderr),r.call(c.stderr,n,...s)},I();}function x(t,e){if(t.length===0)return;let o=new Date;for(let r=0;r<t.length;r++){let n=e[e.length-1];n.timestamp||(n.timestamp=o,n.sequenceId=z++),t[r]===`
|
|
2
|
-
`?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function O(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{y(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{L(o,{timestamp:r,source:"console",sequenceId:n});});}function I(){setTimeout(()=>{O(),I();},1e3);}var l=null;function Q(){}function X(t){l=Object.assign({},l,t);}function S(){return l?.environmentId}function T(){return l?.appAlias}function K(){return l?.environmentAlias}function M(){return l?.telemetry?.serviceName}function a(){return !!l?.telemetry?.isEnabled}var j=false,p=null,b=null,ot=async()=>{if(j)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');j=true,a()&&await P();};async function P(){let t=f("_system.elastic.apmEndpoint"),e=f("_system.elastic.cloudId"),o=f("_system.elastic.apiKey"),r=T()??"unknown",n=K()??"unknown",s=S()??"unknown",g=M();p=B.start({serviceName:g,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:s,appAlias:r,environmentAlias:n}});let u=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});u.on("error",_=>{console.error("Elasticsearch Transport Error:",_);}),b=v.createLogger({level:"debug",defaultMeta:{serviceName:g},format:v.format.combine(v.format.json()),transports:[u]}),h({elasticCloudId:e,elasticApiKey:o});}function A(){if(!p)throw new Error("APM is not initialized");return p}function d(){if(!b)throw new Error("Logger is not initialized");return b}function C(){let t="";return a()||(t="info"),process.env.MODELENCE_LOG_LEVEL||t}function D(t,e){a()&&d().debug(t,e),C()==="debug"&&console.debug(t,e);}function y(t,e){a()&&d().info(t,e),["debug","info"].includes(C())&&console.info(t,e);}function L(t,e){a()&&d().error(t,e),["debug","info","error"].includes(C())&&console.error(t,e);}function W(t,e,o){if(!a())return {end:()=>{},setContext:()=>{}};let r=A(),n=r.startTransaction(e,t);return o&&r.setCustomContext(o),{end:(s,{endTime:g,context:u}={})=>{u&&r.setCustomContext(u),n.end(s,g);},setContext:s=>{r.setCustomContext(s);}}}function q(t){if(!a()){console.error(t);return}A().captureError(t);}export{f as a,U as b,G as c,V as d,Q as e,X as f,ot as g,D as h,y as i,L as j,W as k,q as l};//# sourceMappingURL=chunk-DVECB2TP.js.map
|
|
3
|
-
//# sourceMappingURL=chunk-DVECB2TP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","getLogLevel","defaultLoglevel","logDebug","message","startTransaction","name","context","transaction","result","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAsCb,SAASC,CAAAA,CAAUC,CAAAA,CAAgB,CACxC,OAAOH,CAAAA,CAAOG,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,CAAAA,EAAmB,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,0FACF,CAA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IAAM,EAEX,CACA,UAAA,CAAY,IAAM,EAGpB,CAAA,CAGF,IAAMC,CAAAA,CAAMgB,CAAAA,EAAO,CACbS,CAAAA,CAAczB,CAAAA,CAAI,gBAAA,CAAiBuB,CAAAA,CAAMzD,CAAI,CAAA,CACnD,OAAI0D,CAAAA,EACFxB,CAAAA,CAAI,gBAAA,CAAiBwB,CAAO,CAAA,CAGvB,CACL,GAAA,CAAK,CACHE,CAAAA,CACA,CAAE,OAAA,CAAAC,CAAAA,CAAS,QAAAH,CAAQ,CAAA,CAA6D,EAAC,GAC9E,CACCA,CAAAA,EACFxB,CAAAA,CAAI,gBAAA,CAAiBwB,CAAO,CAAA,CAE9BC,CAAAA,CAAY,GAAA,CAAIC,CAAAA,CAAQC,CAAO,EACjC,CAAA,CACA,UAAA,CAAaH,GAAqC,CAChDxB,CAAAA,CAAI,gBAAA,CAAiBwB,CAAO,EAC9B,CACF,CACF,CAEO,SAASI,CAAAA,CAAad,CAAAA,CAAc,CACzC,GAAI,CAACf,CAAAA,EAAmB,CAAG,CACzB,QAAQ,KAAA,CAAMe,CAAK,CAAA,CACnB,MACF,CAEAE,CAAAA,EAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-DVECB2TP.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n *\n * @param key - The configuration key to retrieve\n * @returns The configuration value (string, number, or boolean)\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the site URL\n * const siteUrl = getConfig('_system.site.url');\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_URL=https://myapp.com\n * ```\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the current environment (e.g., 'development', 'staging', 'production')\n * const env = getConfig('_system.env');\n *\n * if (env === 'production') {\n * // Enable production features\n * }\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_ENV=production\n * ```\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stdout.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stderr.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport,\n ],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\ntype LogLevel = 'error' | 'info' | 'debug' | '';\n\n/**\n * Gets the logging level for console logs based on the MODELENCE_LOG_LEVEL environment variable.\n *\n * @returns The log level ('error' | 'info' | 'debug' | '')\n *\n * Behavior:\n * - If MODELENCE_LOG_LEVEL is set, returns that value\n * - If telemetry is disabled and MODELENCE_LOG_LEVEL is not set, defaults to 'info'\n * - If telemetry is enabled and MODELENCE_LOG_LEVEL is not set, returns '' (no console logging)\n */\nfunction getLogLevel(): LogLevel {\n let defaultLoglevel: LogLevel = '';\n if (!isTelemetryEnabled()) {\n defaultLoglevel = 'info';\n }\n\n return (process.env.MODELENCE_LOG_LEVEL as LogLevel) || defaultLoglevel;\n}\n\nexport function logDebug(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().debug(message, args);\n }\n if (getLogLevel() === 'debug') {\n console.debug(message, args);\n }\n}\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n }\n if (['debug', 'info'].includes(getLogLevel())) {\n console.info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n }\n if (['debug', 'info', 'error'].includes(getLogLevel())) {\n console.error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom' | 'route',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
|