1+ import { BaseObject , KlepperIncomingMessage , KlepperRequest , KlepperResponse , KlepperStackFrame } from "@klepper/transport" ;
2+ import { StackFrame } from "stack-trace" ;
3+
4+ const mapStackFrames = ( stackFrames : StackFrame [ ] , onlyInternal : boolean = true ) => {
5+ const frames : KlepperStackFrame [ ] = [ ] ;
6+
7+ const parse = ( stackFrame : StackFrame ) : KlepperStackFrame => {
8+ return {
9+ functionName : stackFrame . getFunctionName ( ) ,
10+ lineNumber : stackFrame . getLineNumber ( ) ,
11+ columnNumber : stackFrame . getColumnNumber ( ) ,
12+ fileName : stackFrame . getFileName ( ) ,
13+ methodName : stackFrame . getMethodName ( ) ,
14+ }
15+ }
16+
17+ stackFrames . map ( ( f ) => {
18+ if ( onlyInternal ) {
19+ const fileName = f . getFileName ( ) ;
20+ const isInternal = fileName && ! fileName . includes ( 'node_modules' ) && ! fileName . startsWith ( '/' ) && ! fileName . startsWith ( 'node:' ) && fileName . includes ( ":\\" ) ;
21+
22+ isInternal ? frames . push ( parse ( f ) ) : null ;
23+ } else {
24+ frames . push ( parse ( f ) ) ;
25+ }
26+ } ) ;
27+
28+ return frames ;
29+ }
30+
31+ const createPayloadFromRequest = ( req : KlepperRequest , res : KlepperResponse ) => {
32+ return {
33+ request : req ,
34+ response : res ,
35+ date : new Date ( ) . getDate ( )
36+ }
37+ }
38+
39+ const mapRequestData = ( req : BaseObject ) : KlepperRequest => {
40+ const headersData = req . headers || req . header || { } ;
41+
42+ const method = req . method ;
43+ const host = headersData [ "host" ] || '<no host>' ;
44+
45+ const protocol = getProtocol ( req . protocol )
46+
47+ const originalUrl = ( req . originalUrl || req . url ) as string ;
48+ const absoluteUrl = `${ protocol } ://${ host } ${ originalUrl } ` ;
49+ const origin = headersData [ "origin" ] ;
50+ const query = req . query ;
51+ const payload = req . body || { } ;
52+ const ip = getIp ( req as KlepperIncomingMessage ) ;
53+
54+ const connections = {
55+ absoluteUrl,
56+ origin,
57+ protocol
58+ } ;
59+
60+ const headers = {
61+ host,
62+ connection : headersData [ "connection" ] ,
63+ origin : headersData [ "origin" ]
64+ }
65+
66+ const request = {
67+ payload,
68+ headers,
69+ method,
70+ query,
71+ ip,
72+ url : connections ,
73+ } ;
74+
75+ return request ;
76+ }
77+
78+ const getIp = ( req : KlepperIncomingMessage ) : string | string [ ] | undefined => {
79+ return req . headers [ 'x-forwarded-for' ] || req . socket . remoteAddress ;
80+ }
81+
82+ const isLocalhost = ( req : KlepperIncomingMessage ) : boolean => {
83+ const ip = getIp ( req ) ;
84+ return ip === "::1" || ip === "127.0.0.1" ? true : false ;
85+ }
86+
87+ const getProtocol = ( req : KlepperIncomingMessage ) : string => {
88+ return req . protocol === 'https' || req . secure
89+ ? 'https'
90+ : 'http' ;
91+ }
92+
93+
94+ export const helpers = {
95+ getIp,
96+ createPayloadFromRequest,
97+ mapRequestData,
98+ mapStackFrames,
99+ getProtocol,
100+ isLocalhost
101+ }
0 commit comments