@sailfish-ai/sf-veritas 0.2.20 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/consoleLocationTransformer-BSSB5msZ.cjs +1 -0
- package/dist/consoleLocationTransformer-DZu_9MDA.js +51 -0
- package/dist/contextManager-0D8uHQ1_.cjs +1 -0
- package/dist/{contextManager-Dw7Yot7r.js → contextManager-RxrMXs5c.js} +106 -83
- package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
- package/dist/plugins/funcspanEsbuildPlugin.mjs +20 -16
- package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
- package/dist/plugins/funcspanRollupPlugin.mjs +17 -13
- package/dist/plugins/funcspanTscPlugin.cjs +1 -1
- package/dist/plugins/funcspanTscPlugin.mjs +34 -30
- package/dist/plugins/funcspanVitePlugin.cjs +1 -1
- package/dist/plugins/funcspanVitePlugin.mjs +16 -12
- package/dist/plugins/funcspanWebpackLoader.cjs +1 -1
- package/dist/plugins/funcspanWebpackLoader.mjs +55 -50
- package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.mjs +1 -1
- package/dist/runtimeConfig-BZ61efqE.js +485 -0
- package/dist/runtimeConfig-CWpFWsmz.cjs +6 -0
- package/dist/sf-veritas.cjs +25 -13
- package/dist/sf-veritas.mjs +453 -393
- package/dist/telemetryWorker.cjs +1 -0
- package/dist/types/dataTransmitter.d.ts +6 -5
- package/dist/types/exceptionTransmitter.d.ts +2 -1
- package/dist/types/frameworkDetection.d.ts +18 -0
- package/dist/types/networkHopTransmitter.d.ts +2 -1
- package/dist/types/networkRequestTransmitter.d.ts +2 -1
- package/dist/types/plugins/consoleLocationTransformer.d.ts +37 -0
- package/dist/types/requestUtils.d.ts +17 -6
- package/dist/types/setupConfig.d.ts +3 -0
- package/dist/types/sourceLocation.d.ts +19 -19
- package/dist/types/telemetryWorker.d.ts +1 -0
- package/dist/worker-pool-capture.cjs +1 -1
- package/dist/worker-pool-capture.mjs +1 -1
- package/dist/workerPoolSpanCapture-Bg5av6gn.cjs +83 -0
- package/dist/{workerPoolSpanCapture-Dm4Reseo.js → workerPoolSpanCapture-BjdZn3LE.js} +222 -168
- package/package.json +1 -1
- package/dist/contextManager-DQMeQfS_.cjs +0 -1
- package/dist/runtimeConfig-Bfqf33tO.js +0 -444
- package/dist/runtimeConfig-DmD4lUhG.cjs +0 -9
- package/dist/workerPoolSpanCapture-CAM2z9Jx.cjs +0 -83
package/dist/sf-veritas.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./contextManager-0D8uHQ1_.cjs"),p=require("./workerPoolSpanCapture-Bg5av6gn.cjs"),S=require("./runtimeConfig-CWpFWsmz.cjs"),ce=require("node:module"),A=require("fs"),P=require("http"),E=require("https"),de=require("./source-map-rHHEdpre.cjs"),le=require("fs/promises"),ue=require("path"),pe=require("glob"),T=require("worker_threads"),R=require("./funcSpanTransformer-D0W2t41q.cjs");function x(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const ge=x(A),W=x(le),N=x(ue);class w extends p.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!a.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){a.getConfig().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
|
|
2
2
|
${this.queryType} ${this.operationName}(
|
|
3
3
|
$apiKey: String!,
|
|
4
4
|
$timestampMs: String!,
|
|
@@ -13,6 +13,9 @@
|
|
|
13
13
|
$gitRepo: String,
|
|
14
14
|
$gitProvider: String,
|
|
15
15
|
$serviceDisplayName: String,
|
|
16
|
+
$framework: String,
|
|
17
|
+
$additionalFrameworks: JSON,
|
|
18
|
+
$serviceRole: String,
|
|
16
19
|
) {
|
|
17
20
|
${this.queryName}(
|
|
18
21
|
apiKey: $apiKey,
|
|
@@ -28,13 +31,16 @@
|
|
|
28
31
|
gitRepo: $gitRepo,
|
|
29
32
|
gitProvider: $gitProvider,
|
|
30
33
|
serviceDisplayName: $serviceDisplayName,
|
|
34
|
+
framework: $framework,
|
|
35
|
+
additionalFrameworks: $additionalFrameworks,
|
|
36
|
+
serviceRole: $serviceRole,
|
|
31
37
|
)
|
|
32
38
|
}
|
|
33
|
-
`,t=this.getVariables({serviceIdentifier:
|
|
39
|
+
`,t=a.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,library:t.packageLibraryType,version:t.version,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,framework:t.framework||void 0,additionalFrameworks:t.additionalFrameworks.length>0?t.additionalFrameworks:void 0,serviceRole:t.serviceRole||void 0});p.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class fe extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectMetadata")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e,t,i,n){this.startBackgroundIdentify(),this.send(e,t,i,n)}async send(e,t,i,n){if(!t&&!n)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let o=[];if(!n){const c=S.serializeJsonWithExclusions(t);n=c.traitsJson,o=c.excludedFields}const f=this.getVariables({userId:e,traitsJson:n,excludedFields:o,override:i,library:a.getConfig().packageLibraryType,version:a.getConfig().version});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),f)}getQuery(){return`
|
|
34
40
|
mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
|
|
35
41
|
${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
|
|
36
42
|
}
|
|
37
|
-
`}}class K{constructor(e){this.apiKey=e,this.metadataTransmitter=new
|
|
43
|
+
`}}class K{constructor(e){this.apiKey=e,this.metadataTransmitter=new fe}metadataTransmitter;identify(e,t,i,n=!1){t||i?this.addOrUpdateMetadata(e,t,i,n):this.addOrUpdateMetadata(e,{},void 0,n)}addOrUpdateMetadata(e,t={},i,n=!1){if(!t&&!i)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');a.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),a.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class B extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super()}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}async send(e){try{const t=Array.isArray(e)?e:[e,"default",null,null],i=this.getVariables({contents:t[0],level:t[1],sourceFile:t[2]||void 0,sourceLine:t[3]||void 0});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}catch(t){a.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
|
|
38
44
|
${this.queryType} ${this.operationName}(
|
|
39
45
|
$apiKey: String!,
|
|
40
46
|
$serviceUuid: String!,
|
|
@@ -58,7 +64,7 @@
|
|
|
58
64
|
sourceLine: $sourceLine
|
|
59
65
|
)
|
|
60
66
|
}
|
|
61
|
-
`}}class
|
|
67
|
+
`}}class he extends p.BaseTransmitter{serviceIdentifier=new w;supplementalFields={};setSupplementalFields(e){this.supplementalFields={...this.supplementalFields,...e}}normalizedSupplementalForGraphQL(){const{isFromLocalService:e}=this.supplementalFields,t={};return e!==void 0&&(t.isFromLocalService=e),t}constructor(){super(),this.setOperationName("CollectExceptions")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e,t){this.startBackgroundIdentify(),this.send(e,t)}async send(e,t){a.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(S.CustomJSONEncoderForFrameInfo.encode(t)),n=this.normalizedSupplementalForGraphQL(),o=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:a.getConfig().packageLibraryType,version:a.getConfig().version,...n});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}getQuery(){return`
|
|
62
68
|
mutation ${this.operationName}(
|
|
63
69
|
$apiKey: String!,
|
|
64
70
|
$serviceUuid: String!,
|
|
@@ -86,7 +92,7 @@
|
|
|
86
92
|
parentSpanId: $parentSpanId
|
|
87
93
|
)
|
|
88
94
|
}
|
|
89
|
-
`}}const
|
|
95
|
+
`}}const j="getting request source code";var O=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(O||{});const z="http:",me=ce.createRequire(require("node:url").pathToFileURL(__filename).href);let J=!1;function ye(){const r=a.getConfig().sfDebug;if(J)return void(r&&S.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;J=!0;try{e=me("node:http"),r&&S.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void S.internalError("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(r&&S.internalLog("[patchNodeHttpInbound] http.Server.prototype not found."));const t=e.Server.prototype,i=t.emit;i&&!t.__sf_inbound_patched__?(Object.defineProperty(t,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),r&&S.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...o){if(n!=="request")return r&&S.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...o);const f=o[0],c=o[1],s=(function(u){const m={};if(!u)return m;for(const[I,$]of Object.entries(u))$!=null&&(Array.isArray($)?m[I.toLowerCase()]=$.join(", "):m[I.toLowerCase()]=String($));return m})(f?.headers),l=s["x-sf3-rid"],g=s["x-sf3-functionspancaptureoverride"];r&&(S.internalLog("[patchNodeHttpInbound] Intercepted request event."),S.internalLog("[patchNodeHttpInbound] Inbound headers:",s),S.internalLog("[patchNodeHttpInbound] Trace header:",l),S.internalLog("[patchNodeHttpInbound] FuncSpan override header:",g));const d=a.ContextManager.getInstance();d.setTraceId(l);const h=d.getTraceId();r&&S.internalLog("[patchNodeHttpInbound] Context traceId set:",h);const y=()=>d.runWith({inboundHeaders:s,...l?{traceId:l}:{}},()=>{l&&d.setTraceId(l),r&&S.internalLog("[patchNodeHttpInbound] Running request handler in context.");const u=()=>{r&&S.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",d.getTraceId())};return c.on("finish",u),c.on("close",u),i.call(this,n,f,c)});if(!g)return y();try{return p.funcspanOverrideStorage.run(g,()=>y())}catch{return y()}}):r&&S.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class Se extends B{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.send(e)}async send(e){const t=`
|
|
90
96
|
${this.queryType} ${this.operationName}(
|
|
91
97
|
$apiKey: String!,
|
|
92
98
|
$serviceUuid: String!,
|
|
@@ -98,7 +104,7 @@
|
|
|
98
104
|
domains: $domains
|
|
99
105
|
)
|
|
100
106
|
}
|
|
101
|
-
`,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};
|
|
107
|
+
`,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};p.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class ve extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectNetworkHops")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}async send(e){const{name:t,column:i,line:n,entrypoint:o,retryWithoutTraceId:f}=e,c=this.getVariables({name:t,column:i,line:n,entrypoint:o,retryWithoutTraceId:f});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),c)}getQuery(){return`
|
|
102
108
|
mutation ${this.operationName}(
|
|
103
109
|
$apiKey: String!,
|
|
104
110
|
$sessionId: String!,
|
|
@@ -122,15 +128,15 @@
|
|
|
122
128
|
${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
|
|
123
129
|
)
|
|
124
130
|
}
|
|
125
|
-
`}}class Ie extends
|
|
131
|
+
`}}class Ie extends p.BaseTransmitter{serviceIdentifier=new w;constructor(){super(),this.setOperationName("CollectNetworkRequest")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{a.getConfig().serviceIdentificationReceived?clearInterval(e):this.serviceIdentifier.doSend({})},5e3);e&&typeof e=="object"&&"unref"in e&&e.unref()}async doSend(e){this.startBackgroundIdentify(),this.send(e)}getQuery(){return`
|
|
126
132
|
mutation ${this.operationName}(
|
|
127
133
|
$data: NetworkRequestInput!
|
|
128
134
|
) {
|
|
129
135
|
${this.queryName}(
|
|
130
136
|
data: $data)
|
|
131
137
|
}
|
|
132
|
-
`}async send(e){const t={data:{...e}};await
|
|
133
|
-
`).slice(1),
|
|
138
|
+
`}async send(e){const t={data:{...e}};await p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const L=[400,403];class $e{HEADER_TRACING="X-Sf3-Rid";HEADER_LOG_GUARD="reentrancy_guard_logging_preactive";HEADER_PRINT_GUARD="reentrancy_guard_print_preactive";HEADER_EXCEPTION_GUARD="reentrancy_guard_exception_preactive";contextManager;constructor(e=[]){this.contextManager=a.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),a.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let i;if(e instanceof Headers)i=e.get(t)??void 0;else{const o=t.toLowerCase();for(const[f,c]of Object.entries(e))if(f.toLowerCase()===o){i=c;break}}if(!i)return{};const n=i.split("/").filter(Boolean);return n.length<3?{}:{sessionId:n[0],pageVisitId:n[1],requestId:n[n.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,i,n,o]=t;return{filePath:i,line:parseInt(n,10),column:parseInt(o,10)}}async getOriginalPosition(e,t,i){let n={source:e,line:t,column:i,name:null};if(e.includes("://"))return{originalPos:n};const o=e+".map";try{const f=JSON.parse(A.readFileSync(o,"utf-8"));let c=(await new de.sourceMapExports.SourceMapConsumer(f)).originalPositionFor({line:t,column:i});c.source&&(n=c)}catch(f){a.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${o}:`,f)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=a.getConfig().sfDebug?10:t,o=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(o,n);const f=new Error(j);j in Error&&Error.captureStackTrace(f,this.captureFirstUserLines);const c=S.stackToString(f.stack);Error.stackTraceLimit=o;const s=c.split(`
|
|
139
|
+
`).slice(1),l=[];for(const g of s)if(!(g.includes("node:internal")||g.includes("internal/modules")||g.includes("internal/process")||g.includes("node_modules")||g.includes(".next/server/chunks")||g.includes("RequestInterceptor")||g.includes("contextManager")||g.includes("setupConfig"))&&(l.push(g.trim()),l.length>=t))break;for(const g of l){const d=this.parseStackFrame(g);d?(async()=>{const{originalPos:h}=await this.getOriginalPosition(d.filePath,d.line,d.column);if(h){a.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",h);const y={line:h.line?.toString()||O.UNKNOWN,column:h.column?.toString()||O.NOT_CAPTURED,name:h.name||O.NOT_CAPTURED,entrypoint:h.source,retryWithoutTraceId:i};e.doSend(y)}})():a.getConfig().sfDebug&&console.error("Could not parse stack line:",g)}}addReentrancyGuardHeaders(e){e.set(this.HEADER_LOG_GUARD,"true"),e.set(this.HEADER_PRINT_GUARD,"true"),e.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(e){return!a.DEFAULT_DOMAINS_TO_EXCLUDE.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const i=new URL(t).hostname,n=this.shouldPropagateHeaders(i);return n?this.addTracingHeader(e,t):a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(e,t){const i=p.getFuncspanOverride();if(i){const c=p.parseHeaderOverride(i);if(c&&c.sample_rate===0)return void(a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const n=this.contextManager.getOrSetSfTraceId(),o=this.contextManager.getOrSetPageVisitUUID(),f=a.v4();e.set(this.HEADER_TRACING,`${n}/${o}/${f}`),a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(n,o)=>{const f=new Headers(o?.headers);if(f.get(this.HEADER_LOG_GUARD)==="true"||f.get(this.HEADER_PRINT_GUARD)==="true"||f.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,o);this.captureFirstUserLines(e);const c=Date.now();let s;typeof n=="string"||n instanceof URL?s=n.toString():n instanceof Request?(s=n.url,n.headers.forEach((u,m)=>{f.set(m,u)})):a.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),a.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",s);const l=new URL(s).hostname,g=new Headers(f),d=this.addTracingHeaders(f,s),h={...o,headers:f};let y;try{let u=!1;this.addTracingHeaders(g,s),y=await i(s,h),d&&L.includes(y.status)?(y=await i(s,{...o,headers:g}),u=!0,this.captureFirstUserLines(e,10,u)):this.contextManager.addSupportedDomains(l);const m=Date.now();a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${s}, Status: ${y.status}, Duration: ${m-c}ms`);const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(f),v=a.getConfig(),F={apiKey:v.apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:v.serviceUUID,timestampStart:c.toString(),timestampEnd:m.toString(),responseCode:y.status,success:!0,error:null,url:s,method:h.method||"GET",retryWithoutTraceId:u,parentSpanId:a.getCurrentFunctionSpanId()};if(v.captureRequestHeaders){const _={};f.forEach((C,D)=>{_[D]=C}),F.requestHeaders=_}if(v.captureResponseHeaders){const _={};y.headers.forEach((C,D)=>{_[D]=C}),F.responseHeaders=_}if(v.captureRequestBody&&o?.body)try{const _=typeof o.body=="string"?o.body:JSON.stringify(o.body);F.requestBody=_.length>v.requestBodyLimitBytes?_.substring(0,v.requestBodyLimitBytes)+"...[truncated]":_}catch{}if(v.captureResponseBody)try{const _=y.clone(),C=await _.text();F.responseBody=C.length>v.responseBodyLimitBytes?C.substring(0,v.responseBodyLimitBytes)+"...[truncated]":C}catch{}return t.doSend(F),y}catch(u){const m=Date.now();a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${s}, Error: ${u}, Duration: ${m-c}ms`)}}:a.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}setHeader(e,t,i){e instanceof Headers?e.set(t,i):e[t]=i}addTracingHeadersToPlainObject(e,t){const i=new URL(t).hostname,n=this.shouldPropagateHeaders(i);if(n){const o=p.getFuncspanOverride();if(o){const l=p.parseHeaderOverride(o);if(l&&l.sample_rate===0)return a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`),!1}const f=this.contextManager.getOrSetSfTraceId(),c=this.contextManager.getOrSetPageVisitUUID(),s=a.v4();e[this.HEADER_TRACING]=`${f}/${c}/${s}`,a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}else a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`);return n}patchHttp(e,t){if(a.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!P||typeof P.request!="function")return void(a.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=P.request.bind(P),n=E.request.bind(E),o=(s,l,g,d=z)=>{let h,y;if(typeof s=="string"||s instanceof URL){const u=typeof s=="string"?new URL(s):s;h={...typeof l=="object"&&l!==null?l:{},protocol:u.protocol||d,hostname:u.hostname,port:u.port||void 0,path:u.pathname+u.search},y=typeof l=="function"?l:g}else h={...s},h.protocol||(h.protocol=d),y=typeof l=="function"?l:void 0;return h.headers||(h.headers={}),[h,y]},f=(s,l,g)=>{const[d,h]=o(s,l,g,z);try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(e)}catch(u){a.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",u)}let y=!1;return i(d,u=>{const m=`${d.protocol}//${d.hostname}`;if(this.shouldPropagateHeaders(new URL(m).hostname)&&L.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],i(v,h),y=!0,this.captureFirstUserLines(e,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);t.doSend({apiKey:a.getConfig().apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:a.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:u.statusCode||0,success:!!u.statusCode&&u.statusCode<400,error:null,url:m,method:d.method||"GET",retryWithoutTraceId:y,parentSpanId:a.getCurrentFunctionSpanId()}),h?.(u)})},c=(s,l,g)=>{const[d,h]=o(s,l,g,"https:");try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(e)}catch(u){a.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",u)}let y=!1;return n(d,u=>{const m=`${d.protocol}//${d.hostname}`;if(this.shouldPropagateHeaders(new URL(m).hostname)&&L.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],n(v,h),y=!0,this.captureFirstUserLines(e,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);t.doSend({apiKey:a.getConfig().apiKey,requestId:b,pageVisitId:$,recordingSessionId:I,serviceUuid:a.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:u.statusCode||0,success:!!u.statusCode&&u.statusCode<400,error:null,url:m,method:d.method||"GET",retryWithoutTraceId:y,parentSpanId:a.getCurrentFunctionSpanId()}),h?.(u)})};P.request=f,E.request=c,P.get=(s,l,g)=>{const d=f(s,l,g);return d.end(),d},E.get=(s,l,g)=>{const d=c(s,l,g);return d.end(),d},a.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request/get methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class _e extends B{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.send()}async send(){const e=`
|
|
134
140
|
${this.queryType} ${this.operationName}(
|
|
135
141
|
$apiKey: String!,
|
|
136
142
|
$serviceUuid: String!,
|
|
@@ -147,6 +153,9 @@
|
|
|
147
153
|
$infrastructureDetails: JSON,
|
|
148
154
|
$setupInterceptorsFile: String,
|
|
149
155
|
$setupInterceptorsLine: Int,
|
|
156
|
+
$framework: String,
|
|
157
|
+
$additionalFrameworks: JSON,
|
|
158
|
+
$serviceRole: String,
|
|
150
159
|
) {
|
|
151
160
|
${this.queryName}(
|
|
152
161
|
apiKey: $apiKey,
|
|
@@ -164,9 +173,12 @@
|
|
|
164
173
|
infrastructureDetails: $infrastructureDetails,
|
|
165
174
|
setupInterceptorsFile: $setupInterceptorsFile,
|
|
166
175
|
setupInterceptorsLine: $setupInterceptorsLine,
|
|
176
|
+
framework: $framework,
|
|
177
|
+
additionalFrameworks: $additionalFrameworks,
|
|
178
|
+
serviceRole: $serviceRole,
|
|
167
179
|
)
|
|
168
180
|
}
|
|
169
|
-
`,t=c.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,infrastructureType:t.infrastructureType||void 0,infrastructureDetails:t.infrastructureDetails||void 0,setupInterceptorsFile:t.setupInterceptorsFile||void 0,setupInterceptorsLine:t.setupInterceptorsLine||void 0});u.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class $e{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(e=[process.cwd()],t=!1){this.rootPaths=e,this.debug=t||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const e=[];for(const t of this.rootPaths)pe.existsSync(t)?await this._walkDirectory(t,e):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${t}`);e.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${e.length} .sailfish files:`),e.forEach(t=>console.log(`[FuncSpan ConfigLoader] - ${t}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const t of e)await this._loadConfigFile(t);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(e,t){const i=this.hasSailfishFiles?u.getEnvConfig():u.getDefaultConfig(),n=this._getDirectoryConfig(e),s=F.normalize(e),l=this.fileConfigs.get(s)||{};let o={};if(t){const d=this.functionConfigs.get(s);d&&(o=d.get(t)||{})}return u.mergeConfigs(i,n,l,o)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=await W.readdir(e,{withFileTypes:!0});for(const n of i){const s=F.join(e,n.name);n.isFile()&&n.name===".sailfish"?t.push(s):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(s,t)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const t=await W.readFile(e,"utf-8"),i=F.dirname(e);let n=null;try{n=JSON.parse(t)}catch{try{n=require("toml").parse(t)}catch{try{n=require("js-yaml").load(t)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON, TOML, or YAML:`,s))}}}if(!n)return;n.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),n.default&&this.directoryConfigs.set(i,n.default),n.files&&await this._expandFileGlobs(i,n.files,n.default||{}),n.functions&&this._storeFunctionConfigs(i,n.functions,n.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${i}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!n.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(n.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(n.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,i){for(const[n,s]of Object.entries(t))try{const l=F.join(e,n),o=await ue.glob(l,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${o.length} files`);for(const d of o){const a=F.normalize(d),p=u.mergeConfigs(i,s);this.fileConfigs.set(a,p),this.debug&&o.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${d}`)}}catch(l){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,l)}}_storeFunctionConfigs(e,t,i){for(const[n,s]of Object.entries(t)){const l=n.split("::");if(l.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[o,d]=l,a=F.normalize(F.join(e,o));this.functionConfigs.has(a)||this.functionConfigs.set(a,new Map);const p=this.functionConfigs.get(a),h=u.mergeConfigs(i,s);p.set(d,h),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${a}::${d}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=F.dirname(F.normalize(e));const i=[];for(;t&&t!==F.dirname(t);){const n=this.directoryConfigs.get(t);n&&i.unshift(n),t=F.dirname(t)}return i.reduce((n,s)=>u.mergeConfigs(n,s),{})}}const oe="__sf_globalConfigLoader";function se(){return globalThis[oe]??null}async function J(r,e){const t=new $e(r,e);(function(i){globalThis[oe]=i})(t),await t.loadAllConfigs()}function V(r,e){const t=se();return t?t.getConfig(r,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),u.getDefaultConfig())}function Q(){return se()!==null}const be=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],X=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ce=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Fe=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Y=!1;function Ne(r){if(typeof r!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&r.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!r.includes(t))}let Z=!1;function ee(r){if(typeof r!="string")return!1;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&r===new URL(e).hostname)return!0}catch{}return!1}function De(){if(!Z)try{let r;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{r=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(r.__sf_worker_pool_patched__)return;Object.defineProperty(r,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of X)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return u.isSendingInternalTelemetry()?t.apply(this,i):ee(i[0])?t.apply(this,i):typeof i[i.length-1]=="function"?u.captureWorkerPoolOperation("dns",e,t,i,this):t.apply(this,i)},Object.defineProperty(r[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of X)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return u.isSendingInternalTelemetry()?i.apply(this,n):ee(n[0])?i.apply(this,n):u.captureWorkerPoolPromiseOperation("dns",t,i,n,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(r),Z=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let te=!1,ne=!1,M=!1;function re(){if(M)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),u.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Y)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of be)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return Ne(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?u.captureWorkerPoolOperation("fs",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}Y=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),u.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),De()),u.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!te)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ce)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?u.captureWorkerPoolOperation("crypto",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}te=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),u.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!ne)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Fe)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?u.captureWorkerPoolOperation("zlib",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ne=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),M=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function ie(){return M}let k=!1,q=!1,A=null;function T(r){const e=c.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:r.functionName,file:r.filePath,duration:`${r.duration}ms`,async:r.async,error:r.error,spanId:r.spanId});const i={functionName:r.functionName,filePath:r.filePath,metadata:r.metadata,args:r.args,result:r.result,error:r.error,duration:r.duration,durationNs:r.durationNs,async:r.async,spanId:r.spanId,parentSpanId:r.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
|
|
170
|
-
📊 Function Span:`,{function:`${r.functionName} (${r.filePath}:${r.metadata.line}:${r.metadata.column})`,duration:`${r.duration.toFixed(2)}ms`,arguments:r.args,result:r.error?`Error: ${r.error}`:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId||"none"});const n=process.env.SF_FUNCSPAN_JSONL_FILE;if(n)try{const
|
|
171
|
-
`;
|
|
172
|
-
`)[2]||"",
|
|
181
|
+
`,t=a.getConfig(),i=this.getVariables({serviceIdentifier:t.serviceIdentifier,serviceVersion:t.serviceVersion,serviceAdditionalMetadata:t.serviceAdditionalMetadata,gitSha:t.gitSha||"",gitOrg:t.gitOrg||void 0,gitRepo:t.gitRepo||void 0,gitProvider:t.gitProvider||void 0,serviceDisplayName:t.serviceDisplayName||void 0,infrastructureType:t.infrastructureType||void 0,infrastructureDetails:t.infrastructureDetails||void 0,setupInterceptorsFile:t.setupInterceptorsFile||void 0,setupInterceptorsLine:t.setupInterceptorsLine||void 0,framework:t.framework||void 0,additionalFrameworks:t.additionalFrameworks?.length>0?t.additionalFrameworks:void 0,serviceRole:t.serviceRole||void 0});p.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class be{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(e=[process.cwd()],t=!1){this.rootPaths=e,this.debug=t||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const e=[];for(const t of this.rootPaths)ge.existsSync(t)?await this._walkDirectory(t,e):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${t}`);e.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${e.length} .sailfish files:`),e.forEach(t=>console.log(`[FuncSpan ConfigLoader] - ${t}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const t of e)await this._loadConfigFile(t);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(e,t){const i=this.hasSailfishFiles?p.getEnvConfig():p.getDefaultConfig(),n=this._getDirectoryConfig(e),o=N.normalize(e),f=this.fileConfigs.get(o)||{};let c={};if(t){const s=this.functionConfigs.get(o);s&&(c=s.get(t)||{})}return p.mergeConfigs(i,n,f,c)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=await W.readdir(e,{withFileTypes:!0});for(const n of i){const o=N.join(e,n.name);n.isFile()&&n.name===".sailfish"?t.push(o):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(o,t)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const t=await W.readFile(e,"utf-8"),i=N.dirname(e);let n=null;try{n=JSON.parse(t)}catch{try{n=require("toml").parse(t)}catch{try{n=require("js-yaml").load(t)}catch(o){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON, TOML, or YAML:`,o))}}}if(!n)return;n.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),n.default&&this.directoryConfigs.set(i,n.default),n.files&&await this._expandFileGlobs(i,n.files,n.default||{}),n.functions&&this._storeFunctionConfigs(i,n.functions,n.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${i}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!n.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(n.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(n.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,i){for(const[n,o]of Object.entries(t))try{const f=N.join(e,n),c=await pe.glob(f,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${c.length} files`);for(const s of c){const l=N.normalize(s),g=p.mergeConfigs(i,o);this.fileConfigs.set(l,g),this.debug&&c.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${s}`)}}catch(f){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,f)}}_storeFunctionConfigs(e,t,i){for(const[n,o]of Object.entries(t)){const f=n.split("::");if(f.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[c,s]=f,l=N.normalize(N.join(e,c));this.functionConfigs.has(l)||this.functionConfigs.set(l,new Map);const g=this.functionConfigs.get(l),d=p.mergeConfigs(i,o);g.set(s,d),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${l}::${s}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=N.dirname(N.normalize(e));const i=[];for(;t&&t!==N.dirname(t);){const n=this.directoryConfigs.get(t);n&&i.unshift(n),t=N.dirname(t)}return i.reduce((n,o)=>p.mergeConfigs(n,o),{})}}const se="__sf_globalConfigLoader";function ae(){return globalThis[se]??null}async function V(r,e){const t=new be(r,e);(function(i){globalThis[se]=i})(t),await t.loadAllConfigs()}function Q(r,e){const t=ae();return t?t.getConfig(r,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),p.getDefaultConfig())}function X(){return ae()!==null}const Fe=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Y=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ce=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ne=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Z=!1;function De(r){if(typeof r!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&r.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!r.includes(t))}let ee=!1;function te(r){if(typeof r!="string")return!1;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&r===new URL(e).hostname)return!0}catch{}return!1}function Pe(){if(!ee)try{let r;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{r=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(r.__sf_worker_pool_patched__)return;Object.defineProperty(r,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Y)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return p.isSendingInternalTelemetry()?t.apply(this,i):te(i[0])?t.apply(this,i):typeof i[i.length-1]=="function"?p.captureWorkerPoolOperation("dns",e,t,i,this):t.apply(this,i)},Object.defineProperty(r[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Y)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return p.isSendingInternalTelemetry()?i.apply(this,n):te(n[0])?i.apply(this,n):p.captureWorkerPoolPromiseOperation("dns",t,i,n,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(r),ee=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let ne=!1,re=!1,H=!1;function ie(){if(H)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),p.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Z)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Fe)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return De(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?p.captureWorkerPoolOperation("fs",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}Z=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),p.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),Pe()),p.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ne)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ce)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?p.captureWorkerPoolOperation("crypto",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ne=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),p.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!re)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ne)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?p.captureWorkerPoolOperation("zlib",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}re=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),H=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function oe(){return H}let U=!1,q=!1,M=null;function k(r){const e=a.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:r.functionName,file:r.filePath,duration:`${r.duration}ms`,async:r.async,error:r.error,spanId:r.spanId});const i={functionName:r.functionName,filePath:r.filePath,metadata:r.metadata,args:r.args,result:r.result,error:r.error,duration:r.duration,durationNs:r.durationNs,async:r.async,spanId:r.spanId,parentSpanId:r.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
|
|
182
|
+
📊 Function Span:`,{function:`${r.functionName} (${r.filePath}:${r.metadata.line}:${r.metadata.column})`,duration:`${r.duration.toFixed(2)}ms`,arguments:r.args,result:r.error?`Error: ${r.error}`:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId||"none"});const n=process.env.SF_FUNCSPAN_JSONL_FILE;if(n)try{const o=n==="true"||n==="1"?"funcspans.jsonl":n,f=Date.now(),c=process.hrtime.bigint(),s=BigInt(r.startTimeNs),l=Number(c-s)/1e6,g=new Date(f-l).toISOString(),d=JSON.stringify({timestamp:g,functionName:r.functionName,filePath:r.filePath,line:r.metadata.line,column:r.metadata.column,duration:r.duration,durationNs:r.durationNs,startTimeNs:r.startTimeNs,arguments:r.args,returnValue:r.error?{error:String(r.error)}:r.result,spanId:r.spanId,parentSpanId:r.parentSpanId,async:r.async,pid:r.pid,threadId:r.threadId})+`
|
|
183
|
+
`;A.appendFileSync(o,d,"utf-8")}catch(o){console.error("[FuncSpan] Error writing to JSONL file:",o)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(M||(M=new p.FunctionSpanTransmitter),M).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(o){t&&console.error("[FuncSpan] Error sending function span:",o)}}exports.ContextManager=a.ContextManager,exports.getCurrentFunctionSpanId=a.getCurrentFunctionSpanId,exports.runWithContext=a.runWithContext,exports.clearFuncspanOverride=p.clearFuncspanOverride,exports.getDefaultConfig=p.getDefaultConfig,exports.getEnvConfig=p.getEnvConfig,exports.getFuncspanOverride=p.getFuncspanOverride,exports.parseHeaderOverride=p.parseHeaderOverride,exports.setFuncspanOverride=p.setFuncspanOverride,exports.isProductionEnvironment=S.isProductionEnvironment,exports.isRuntimeModeEnabled=S.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=S.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=R.setSkipTypeScriptPlugin,exports.transformFunctionSpans=R.transformFunctionSpans,exports.transformFunctionSpansSync=R.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=a.getConfig();new K(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...o){const f=a.getGlobalConfigUnsafe(),c=f?.sfDebug||!1;c&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const s=(function(m,I){const $=p.getFuncspanOverride();if($){const b=p.parseHeaderOverride($);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${m}::${I}`),b}try{return Q(m,I)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(c&&console.log(`[FuncSpan] Config for ${t}::${e}:`,s),s.enable_sampling&&s.sample_rate<1&&Math.random()>s.sample_rate)return c&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,o);if(s.sample_rate===0)return c&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,o);c&&console.log(`[FuncSpan] Capturing function span for ${e}`);const l=a.ContextManager.getInstance(),g=l.getCurrentFunctionSpanId(),d=a.v4();l.setCurrentFunctionSpanId(d);const h=process.hrtime.bigint(),y=Date.now();let u=null;s.capture_arguments&&(u={},i.paramNames.forEach((m,I)=>{I<o.length&&(u[m]=o[I])}),u&&s.arg_limit_mb>0&&(u=p.truncateToLimit(u,s.arg_limit_mb)));try{const m=r.apply(this,o);if(m&&typeof m.then=="function")return g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),m.then(F=>{const _=process.hrtime.bigint(),C=Date.now(),D=Number(_-h);let G=null;return s.capture_return_value&&s.return_limit_mb>0&&(G=p.truncateToLimit(F,s.return_limit_mb)),k({functionName:e,filePath:t,metadata:i,args:u,result:G,error:null,duration:C-y,durationNs:D,startTimeNs:h.toString(),async:!0,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),F},F=>{const _=process.hrtime.bigint(),C=Date.now(),D=Number(_-h);throw k({functionName:e,filePath:t,metadata:i,args:u,result:null,error:F?.message||String(F),duration:C-y,durationNs:D,startTimeNs:h.toString(),async:!0,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),F});const I=process.hrtime.bigint(),$=Date.now(),b=Number(I-h);let v=null;return s.capture_return_value&&s.return_limit_mb>0&&(v=p.truncateToLimit(m,s.return_limit_mb)),k({functionName:e,filePath:t,metadata:i,args:u,result:v,error:null,duration:$-y,durationNs:b,startTimeNs:h.toString(),async:!1,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),m}catch(m){const I=process.hrtime.bigint(),$=Date.now(),b=Number(I-h);throw k({functionName:e,filePath:t,metadata:i,args:u,result:null,error:m?.message||String(m),duration:$-y,durationNs:b,startTimeNs:h.toString(),async:!1,spanId:d,parentSpanId:g,pid:process.pid,threadId:T.threadId}),g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),m}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const o in r)r.hasOwnProperty(o)&&(n[o]=r[o]);return n},exports.getGlobalConfig=Q,exports.identify=function(r,e,t,i=!1){const n=a.getConfig();new K(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=V,exports.initializeWorkerPoolPatching=ie,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=X,exports.isSetupInterceptorsInitialized=function(){return U},exports.isWorkerPoolInitialized=oe,exports.setupInterceptors=function(r){if(q)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!U){q=!0,p.registerShutdownHooks();try{let e,t;const i=S.stackToString(new Error().stack);if(i){const c=i.split(`
|
|
184
|
+
`)[2]||"",s=c.match(/\((.+):(\d+):\d+\)/)||c.match(/at (.+):(\d+):\d+/);s&&(e=s[1],t=parseInt(s[2],10))}if(!r||!r.apiKey){const c=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(c)}const{config:n}=a.getOrCreateConfig(r);if(a.backfillGitInfoAsync(n).catch(()=>{}),e&&(n.setupInterceptorsFile=e),t&&(n.setupInterceptorsLine=t),n.sfDebug&&console.log("Updated configuration after applying options:",n),!n.apiKey||!n.apiGraphqlEndpoint){const c=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(c),new Error(c)}X()||V(void 0,n.sfDebug).catch(c=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",c)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):oe()||(ie(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const o=new B;o.setServiceUUID(n.serviceUUID),S.initializeLogInterceptor(o),(function(c=[]){const s=new $e(c);new Se().doSend(s.getExcludedDomains());const l=new ve,g=new Ie;s.patchFetch(l,g),s.patchHttp(l,g)})(n.domainsToNotPropagateHeadersTo);const f=new he;f.setServiceUUID(n.serviceUUID),S.initializeExceptionInterceptor(f),ye(),new _e().send(),U=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{q=!1}}};
|