@sailfish-ai/sf-veritas 0.2.21 → 0.3.1
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/README.md +53 -0
- package/dist/consoleLocationTransformer-BSSB5msZ.cjs +1 -0
- package/dist/consoleLocationTransformer-DZu_9MDA.js +51 -0
- package/dist/contextManager-BsolAr_q.cjs +1 -0
- package/dist/{contextManager-RxrMXs5c.js → contextManager-D2ijKL-E.js} +105 -102
- 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-C4mv7SVM.js +484 -0
- package/dist/runtimeConfig-XIm4yAFB.cjs +6 -0
- package/dist/sf-veritas.cjs +13 -13
- package/dist/sf-veritas.mjs +532 -388
- 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/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/requestTransmitter.d.ts +45 -0
- package/dist/types/requestUtils.d.ts +17 -6
- package/dist/types/setupConfig.d.ts +21 -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-DzCJnMDA.cjs +83 -0
- package/dist/{workerPoolSpanCapture-DVYmzgbN.js → workerPoolSpanCapture-hyxgVqUF.js} +222 -168
- package/package.json +17 -1
- package/dist/contextManager-0D8uHQ1_.cjs +0 -1
- package/dist/runtimeConfig-CB57auSb.js +0 -444
- package/dist/runtimeConfig-sm_7bnKx.cjs +0 -9
- package/dist/workerPoolSpanCapture-DFnbcpkU.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 o=require("./contextManager-BsolAr_q.cjs"),l=require("./workerPoolSpanCapture-DzCJnMDA.cjs"),F=require("./runtimeConfig-XIm4yAFB.cjs"),ge=require("node:module"),K=require("fs"),T=require("http"),O=require("https"),fe=require("./source-map-rHHEdpre.cjs"),he=require("fs/promises"),me=require("path"),ye=require("glob"),R=require("worker_threads"),M=require("./funcSpanTransformer-D0W2t41q.cjs");function j(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 Se=j(K),V=j(he),E=j(me);class k extends l.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!o.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){o.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!,
|
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
serviceRole: $serviceRole,
|
|
37
37
|
)
|
|
38
38
|
}
|
|
39
|
-
`,
|
|
39
|
+
`,t=o.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});l.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class Ie extends l.BaseTransmitter{serviceIdentifier=new k;constructor(){super(),this.setOperationName("CollectMetadata")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.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 s=[];if(!n){const c=F.serializeJsonWithExclusions(t);n=c.traitsJson,s=c.excludedFields}const p=this.getVariables({userId:e,traitsJson:n,excludedFields:s,override:i,library:o.getConfig().packageLibraryType,version:o.getConfig().version});l.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),p)}getQuery(){return`
|
|
40
40
|
mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
|
|
41
41
|
${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
|
|
42
42
|
}
|
|
43
|
-
`}}class
|
|
43
|
+
`}}class J{constructor(e){this.apiKey=e,this.metadataTransmitter=new Ie}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"');o.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),o.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class z extends l.BaseTransmitter{serviceIdentifier=new k;constructor(){super()}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.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});l.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}catch(t){o.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
|
|
44
44
|
${this.queryType} ${this.operationName}(
|
|
45
45
|
$apiKey: String!,
|
|
46
46
|
$serviceUuid: String!,
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
sourceLine: $sourceLine
|
|
65
65
|
)
|
|
66
66
|
}
|
|
67
|
-
`}}class
|
|
67
|
+
`}}class ve extends l.BaseTransmitter{serviceIdentifier=new k;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(()=>{o.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){o.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(F.CustomJSONEncoderForFrameInfo.encode(t)),n=this.normalizedSupplementalForGraphQL(),s=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:o.getConfig().packageLibraryType,version:o.getConfig().version,...n});l.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
|
|
68
68
|
mutation ${this.operationName}(
|
|
69
69
|
$apiKey: String!,
|
|
70
70
|
$serviceUuid: String!,
|
|
@@ -92,7 +92,7 @@
|
|
|
92
92
|
parentSpanId: $parentSpanId
|
|
93
93
|
)
|
|
94
94
|
}
|
|
95
|
-
`}}const
|
|
95
|
+
`}}const Q="getting request source code";var L=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(L||{});const X="http:",$e=ge.createRequire(require("node:url").pathToFileURL(__filename).href);let Y=!1;function be(){const r=o.getConfig().sfDebug;if(Y)return void(r&&F.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;Y=!0;try{e=$e("node:http"),r&&F.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void F.internalError("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(r&&F.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&&F.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...s){if(n!=="request")return r&&F.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...s);const p=s[0],c=s[1],a=(function(I){const m={};if(!I)return m;for(const[f,v]of Object.entries(I))v!=null&&(Array.isArray(v)?m[f.toLowerCase()]=v.join(", "):m[f.toLowerCase()]=String(v));return m})(p?.headers),d=a["x-sf3-rid"],g=a["x-sf3-functionspancaptureoverride"];r&&(F.internalLog("[patchNodeHttpInbound] Intercepted request event."),F.internalLog("[patchNodeHttpInbound] Inbound headers:",a),F.internalLog("[patchNodeHttpInbound] Trace header:",d),F.internalLog("[patchNodeHttpInbound] FuncSpan override header:",g));const u=o.ContextManager.getInstance();u.setTraceId(d);const S=u.getTraceId();r&&F.internalLog("[patchNodeHttpInbound] Context traceId set:",S);const b=()=>u.runWith({inboundHeaders:a,...d?{traceId:d}:{}},()=>{d&&u.setTraceId(d),r&&F.internalLog("[patchNodeHttpInbound] Running request handler in context.");const I=()=>{r&&F.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",u.getTraceId())};return c.on("finish",I),c.on("close",I),i.call(this,n,p,c)});if(!g)return b();try{return l.funcspanOverrideStorage.run(g,()=>b())}catch{return b()}}):r&&F.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class _e extends z{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.send(e)}async send(e){const t=`
|
|
96
96
|
${this.queryType} ${this.operationName}(
|
|
97
97
|
$apiKey: String!,
|
|
98
98
|
$serviceUuid: String!,
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
domains: $domains
|
|
105
105
|
)
|
|
106
106
|
}
|
|
107
|
-
`,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:
|
|
107
|
+
`,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};l.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class Ce extends l.BaseTransmitter{serviceIdentifier=new k;constructor(){super(),this.setOperationName("CollectNetworkHops")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.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:s,retryWithoutTraceId:p}=e,c=this.getVariables({name:t,column:i,line:n,entrypoint:s,retryWithoutTraceId:p});l.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),c)}getQuery(){return`
|
|
108
108
|
mutation ${this.operationName}(
|
|
109
109
|
$apiKey: String!,
|
|
110
110
|
$sessionId: String!,
|
|
@@ -128,15 +128,15 @@
|
|
|
128
128
|
${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
|
|
129
129
|
)
|
|
130
130
|
}
|
|
131
|
-
`}}class
|
|
131
|
+
`}}class Fe extends l.BaseTransmitter{serviceIdentifier=new k;constructor(){super(),this.setOperationName("CollectNetworkRequest")}identifyStarted=!1;startBackgroundIdentify(){if(this.identifyStarted)return;this.identifyStarted=!0,this.serviceIdentifier.doSend({});const e=setInterval(()=>{o.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`
|
|
132
132
|
mutation ${this.operationName}(
|
|
133
133
|
$data: NetworkRequestInput!
|
|
134
134
|
) {
|
|
135
135
|
${this.queryName}(
|
|
136
136
|
data: $data)
|
|
137
137
|
}
|
|
138
|
-
`}async send(
|
|
139
|
-
`).slice(1),l=[];for(const p of s)if(!(p.includes("node:internal")||p.includes("internal/modules")||p.includes("internal/process")||p.includes("node_modules")||p.includes(".next/server/chunks")||p.includes("RequestInterceptor")||p.includes("contextManager")||p.includes("setupConfig"))&&(l.push(p.trim()),l.length>=e))break;for(const p of l){const d=this.parseStackFrame(p);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()||k.UNKNOWN,column:h.column?.toString()||k.NOT_CAPTURED,name:h.name||k.NOT_CAPTURED,entrypoint:h.source,retryWithoutTraceId:i};t.doSend(y)}})():a.getConfig().sfDebug&&console.error("Could not parse stack line:",p)}}addReentrancyGuardHeaders(t){t.set(this.HEADER_LOG_GUARD,"true"),t.set(this.HEADER_PRINT_GUARD,"true"),t.set(this.HEADER_EXCEPTION_GUARD,"true")}shouldPropagateHeaders(t){return!a.DEFAULT_DOMAINS_TO_EXCLUDE.some(e=>new RegExp(`^${e.replace(/\*/g,".*")}$`).test(t))}addTracingHeaders(t,e){const i=new URL(e).hostname,n=this.shouldPropagateHeaders(i);return n?this.addTracingHeader(t,e):a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(t,e){const i=g.getFuncspanOverride();if(i){const c=g.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 ${e}`))}const n=this.contextManager.getOrSetSfTraceId(),o=this.contextManager.getOrSetPageVisitUUID(),f=a.v4();t.set(this.HEADER_TRACING,`${n}/${o}/${f}`),a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}patchFetch(t,e){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(t);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,p=new Headers(f),d=this.addTracingHeaders(f,s),h={...o,headers:f};let y;try{let u=!1;this.addTracingHeaders(p,s),y=await i(s,h),d&&R.includes(y.status)?(y=await i(s,{...o,headers:p}),u=!0,this.captureFirstUserLines(t,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 e.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(t,e,i){t instanceof Headers?t.set(e,i):t[e]=i}addTracingHeadersToPlainObject(t,e){const i=new URL(e).hostname,n=this.shouldPropagateHeaders(i);if(n){const o=g.getFuncspanOverride();if(o){const l=g.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 ${e}`),!1}const f=this.contextManager.getOrSetSfTraceId(),c=this.contextManager.getOrSetPageVisitUUID(),s=a.v4();t[this.HEADER_TRACING]=`${f}/${c}/${s}`,a.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${e}`)}else a.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`);return n}patchHttp(t,e){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,p,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:p}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,p)=>{const[d,h]=o(s,l,p,z);try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(t)}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)&&R.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],i(v,h),y=!0,this.captureFirstUserLines(t,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);e.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,p)=>{const[d,h]=o(s,l,p,"https:");try{const u=`${d.protocol}//${d.hostname}`;this.addTracingHeadersToPlainObject(d.headers,u),this.captureFirstUserLines(t)}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)&&R.includes(u.statusCode||0)){const v={...d,headers:{...d.headers}};delete v.headers[this.HEADER_TRACING],n(v,h),y=!0,this.captureFirstUserLines(t,10,y)}const{sessionId:I,pageVisitId:$,requestId:b}=this.extractIdsFromTraceHeader(d.headers);e.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,p)=>{const d=f(s,l,p);return d.end(),d},E.get=(s,l,p)=>{const d=c(s,l,p);return d.end(),d},a.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request/get methods patched globally.")}tryPatch(t,e){try{require.resolve(e),t()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class _e extends B{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const t=`
|
|
138
|
+
`}async send(e){const t={data:{...e}};await l.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const H=[400,403];function A(r,e){return e!=="none"&&(e==="all"||r==="GET"||r==="HEAD"||r==="OPTIONS")}class De{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=o.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),o.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 s=t.toLowerCase();for(const[p,c]of Object.entries(e))if(p.toLowerCase()===s){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,s]=t;return{filePath:i,line:parseInt(n,10),column:parseInt(s,10)}}async getOriginalPosition(e,t,i){let n={source:e,line:t,column:i,name:null};if(e.includes("://"))return{originalPos:n};const s=e+".map";try{const p=JSON.parse(K.readFileSync(s,"utf-8"));let c=(await new fe.sourceMapExports.SourceMapConsumer(p)).originalPositionFor({line:t,column:i});c.source&&(n=c)}catch(p){o.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,p)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=o.getConfig().sfDebug?10:t,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,n);const p=new Error(Q);Q in Error&&Error.captureStackTrace(p,this.captureFirstUserLines);const c=F.stackToString(p.stack);Error.stackTraceLimit=s;const a=c.split(`
|
|
139
|
+
`).slice(1),d=[];for(const g of a)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"))&&(d.push(g.trim()),d.length>=t))break;for(const g of d){const u=this.parseStackFrame(g);u?(async()=>{const{originalPos:S}=await this.getOriginalPosition(u.filePath,u.line,u.column);if(S){o.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",S);const b={line:S.line?.toString()||L.UNKNOWN,column:S.column?.toString()||L.NOT_CAPTURED,name:S.name||L.NOT_CAPTURED,entrypoint:S.source,retryWithoutTraceId:i};e.doSend(b)}})():o.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!o.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):o.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(e,t){const i=l.getFuncspanOverride();if(i){const c=l.parseHeaderOverride(i);if(c&&c.sample_rate===0)return void(o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const n=this.contextManager.getOrSetSfTraceId(),s=this.contextManager.getOrSetPageVisitUUID(),p=o.v4();e.set(this.HEADER_TRACING,`${n}/${s}/${p}`),o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(n,s)=>{const p=new Headers(s?.headers);if(p.get(this.HEADER_LOG_GUARD)==="true"||p.get(this.HEADER_PRINT_GUARD)==="true"||p.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,s);this.captureFirstUserLines(e);const c=Date.now();let a,d="GET";if(typeof n=="string"||n instanceof URL)a=n.toString(),d=(s?.method||"GET").toUpperCase();else{if(!(n instanceof Request))return o.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),i(n,s);a=n.url,d=n.method.toUpperCase(),n.headers.forEach((h,D)=>{p.set(D,h)})}o.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",a);let g="unknown";try{g=new URL(a).hostname}catch{return o.getConfig().sfDebug&&console.warn(`[RequestInterceptor] Could not parse URL '${a}' — passing through without tracing headers.`),i(n,s)}const u=new Headers(p),S=this.addTracingHeaders(p,a),b=h=>n instanceof Request?[new Request(n,{...s||{},headers:h}),void 0]:[a,{...s,headers:h}],I=o.getConfig().retryOnClientError;let m,f=!1;try{const[h,D]=b(p);if(m=await i(h,D),S&&A(d,I)&&H.includes(m.status)){const[$,_]=b(u);m=await i($,_),f=!0;try{this.captureFirstUserLines(e,10,f)}catch(C){o.getConfig().sfDebug&&console.error("[RequestInterceptor] captureFirstUserLines (retry) failed:",C)}}else try{this.contextManager.addSupportedDomains(g)}catch($){o.getConfig().sfDebug&&console.error("[RequestInterceptor] addSupportedDomains failed:",$)}}catch(h){const D=Date.now();o.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${a}, Error: ${h}, Duration: ${D-c}ms`);try{const{sessionId:$,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(p),P=o.getConfig();t.doSend({apiKey:P.apiKey,requestId:C,pageVisitId:_,recordingSessionId:$,serviceUuid:P.serviceUUID,timestampStart:c.toString(),timestampEnd:D.toString(),responseCode:0,success:!1,error:h instanceof Error?h.message:typeof h=="string"?h:JSON.stringify(h),url:a,method:d,retryWithoutTraceId:f,parentSpanId:o.getCurrentFunctionSpanId()})}catch($){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error telemetry send failed:",$)}throw h}const v=Date.now();try{o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${a}, Status: ${m.status}, Duration: ${v-c}ms`);const{sessionId:h,pageVisitId:D,requestId:$}=this.extractIdsFromTraceHeader(p),_=o.getConfig(),C={apiKey:_.apiKey,requestId:$,pageVisitId:D,recordingSessionId:h,serviceUuid:_.serviceUUID,timestampStart:c.toString(),timestampEnd:v.toString(),responseCode:m.status,success:!0,error:null,url:a,method:d,retryWithoutTraceId:f,parentSpanId:o.getCurrentFunctionSpanId()};if(_.captureRequestHeaders){const y={};p.forEach((w,N)=>{y[N]=w}),C.requestHeaders=y}if(_.captureResponseHeaders){const y={};m.headers.forEach((w,N)=>{y[N]=w}),C.responseHeaders=y}if(_.captureRequestBody&&s?.body){const y=s.body,w=_.requestBodyLimitBytes;try{if(typeof y=="string")C.requestBody=y.length>w?y.substring(0,w)+"...[truncated]":y;else if(y instanceof URLSearchParams){const N=y.toString();C.requestBody=N.length>w?N.substring(0,w)+"...[truncated]":N}else if(typeof ArrayBuffer<"u"&&(y instanceof ArrayBuffer||ArrayBuffer.isView(y))){const N=y.byteLength??y.byteLength;C.requestBody=`[binary body, ${N} bytes — not captured]`}else if(typeof Blob<"u"&&y instanceof Blob)C.requestBody=`[Blob, ${y.size} bytes, type=${y.type||"unknown"} — not captured]`;else if(typeof FormData<"u"&&y instanceof FormData)C.requestBody="[FormData — not captured]";else if(typeof ReadableStream<"u"&&y instanceof ReadableStream)C.requestBody="[ReadableStream — not captured]";else{const N=JSON.stringify(y);N&&N!=="{}"&&(C.requestBody=N.length>w?N.substring(0,w)+"...[truncated]":N)}}catch{}}let P;if(_.captureResponseBody){const y=(m.headers.get("content-type")||"").toLowerCase();if(!y||y.includes("json")||y.includes("xml")||y.includes("text/")||y.includes("javascript")||y.includes("ecmascript")||y.includes("x-www-form-urlencoded")||y.includes("application/graphql")){const w=m.clone(),N=_.responseBodyLimitBytes;P=(async()=>{try{const q=await w.text(),pe=q.length>N?q.substring(0,N)+"...[truncated]":q;try{t.doSend({...C,responseBody:pe})}catch{}}catch{}})(),P.catch(()=>{})}else C.responseBody=`[non-text body, content-type=${y} — not captured]`}P||t.doSend(C)}catch(h){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):",h)}return m}:o.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 s=l.getFuncspanOverride();if(s){const d=l.parseHeaderOverride(s);if(d&&d.sample_rate===0)return o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`),!1}const p=this.contextManager.getOrSetSfTraceId(),c=this.contextManager.getOrSetPageVisitUUID(),a=o.v4();e[this.HEADER_TRACING]=`${p}/${c}/${a}`,o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}else o.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`);return n}patchHttp(e,t){if(o.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!T||typeof T.request!="function")return void(o.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=T.request.bind(T),n=O.request.bind(O),s=(a,d,g,u=X)=>{let S,b;if(typeof a=="string"||a instanceof URL){const I=typeof a=="string"?new URL(a):a;S={...typeof d=="object"&&d!==null?d:{},protocol:I.protocol||u,hostname:I.hostname,port:I.port||void 0,path:I.pathname+I.search},b=typeof d=="function"?d:g}else S={...a},S.protocol||(S.protocol=u),b=typeof d=="function"?d:void 0;return S.headers||(S.headers={}),[S,b]},p=(a,d,g)=>{const[u,S]=s(a,d,g,X);try{const f=`${u.protocol}//${u.hostname}`;this.addTracingHeadersToPlainObject(u.headers,f),this.captureFirstUserLines(e)}catch(f){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",f)}const b=(u.method||"GET").toUpperCase(),I=o.getConfig().retryOnClientError,m=(f,v,h)=>{try{const{sessionId:D,pageVisitId:$,requestId:_}=this.extractIdsFromTraceHeader(u.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:_,pageVisitId:$,recordingSessionId:D,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!!f.statusCode&&f.statusCode<400,error:null,url:v,method:b,retryWithoutTraceId:h,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}S?.(f)};return i(u,f=>{const v=`${u.protocol}//${u.hostname}`;let h=!1;try{h=this.shouldPropagateHeaders(new URL(v).hostname)}catch{h=!1}if(h&&A(b,I)&&H.includes(f.statusCode||0)){f.resume();try{const{sessionId:$,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(u.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:C,pageVisitId:_,recordingSessionId:$,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!1,error:null,url:v,method:b,retryWithoutTraceId:!1,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(e,10,!0)}catch{}const D={...u,headers:{...u.headers}};return delete D.headers[this.HEADER_TRACING],void i(D,$=>{m($,v,!0)}).end()}m(f,v,!1)})},c=(a,d,g)=>{const[u,S]=s(a,d,g,"https:");try{const f=`${u.protocol}//${u.hostname}`;this.addTracingHeadersToPlainObject(u.headers,f),this.captureFirstUserLines(e)}catch(f){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",f)}const b=(u.method||"GET").toUpperCase(),I=o.getConfig().retryOnClientError,m=(f,v,h)=>{try{const{sessionId:D,pageVisitId:$,requestId:_}=this.extractIdsFromTraceHeader(u.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:_,pageVisitId:$,recordingSessionId:D,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!!f.statusCode&&f.statusCode<400,error:null,url:v,method:b,retryWithoutTraceId:h,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}S?.(f)};return n(u,f=>{const v=`${u.protocol}//${u.hostname}`;let h=!1;try{h=this.shouldPropagateHeaders(new URL(v).hostname)}catch{h=!1}if(h&&A(b,I)&&H.includes(f.statusCode||0)){f.resume();try{const{sessionId:$,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(u.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:C,pageVisitId:_,recordingSessionId:$,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!1,error:null,url:v,method:b,retryWithoutTraceId:!1,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(e,10,!0)}catch{}const D={...u,headers:{...u.headers}};return delete D.headers[this.HEADER_TRACING],void n(D,$=>{m($,v,!0)}).end()}m(f,v,!1)})};T.request=p,O.request=c,T.get=(a,d,g)=>{const u=p(a,d,g);return u.end(),u},O.get=(a,d,g)=>{const u=c(a,d,g);return u.end(),u},o.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 Ne extends z{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.send()}async send(){const e=`
|
|
140
140
|
${this.queryType} ${this.operationName}(
|
|
141
141
|
$apiKey: String!,
|
|
142
142
|
$serviceUuid: String!,
|
|
@@ -178,7 +178,7 @@
|
|
|
178
178
|
serviceRole: $serviceRole,
|
|
179
179
|
)
|
|
180
180
|
}
|
|
181
|
-
`,e=a.getConfig(),i=this.getVariables({serviceIdentifier:e.serviceIdentifier,serviceVersion:e.serviceVersion,serviceAdditionalMetadata:e.serviceAdditionalMetadata,gitSha:e.gitSha||"",gitOrg:e.gitOrg||void 0,gitRepo:e.gitRepo||void 0,gitProvider:e.gitProvider||void 0,serviceDisplayName:e.serviceDisplayName||void 0,infrastructureType:e.infrastructureType||void 0,infrastructureDetails:e.infrastructureDetails||void 0,setupInterceptorsFile:e.setupInterceptorsFile||void 0,setupInterceptorsLine:e.setupInterceptorsLine||void 0,framework:e.framework||void 0,additionalFrameworks:e.additionalFrameworks?.length>0?e.additionalFrameworks:void 0,serviceRole:e.serviceRole||void 0});g.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class be{rootPaths;fileConfigs=new Map;functionConfigs=new Map;directoryConfigs=new Map;hasSailfishFiles=!1;runtimeModeEnabled=!1;debug;constructor(t=[process.cwd()],e=!1){this.rootPaths=t,this.debug=e||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const t=[];for(const e of this.rootPaths)ge.existsSync(e)?await this._walkDirectory(e,t):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${e}`);t.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${t.length} .sailfish files:`),t.forEach(e=>console.log(`[FuncSpan ConfigLoader] - ${e}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const e of t)await this._loadConfigFile(e);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(t,e){const i=this.hasSailfishFiles?g.getEnvConfig():g.getDefaultConfig(),n=this._getDirectoryConfig(t),o=N.normalize(t),f=this.fileConfigs.get(o)||{};let c={};if(e){const s=this.functionConfigs.get(o);s&&(c=s.get(e)||{})}return g.mergeConfigs(i,n,f,c)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(t,e){try{const i=await W.readdir(t,{withFileTypes:!0});for(const n of i){const o=N.join(t,n.name);n.isFile()&&n.name===".sailfish"?e.push(o):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(o,e)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${t}:`,i)}}async _loadConfigFile(t){try{const e=await W.readFile(t,"utf-8"),i=N.dirname(t);let n=null;try{n=JSON.parse(e)}catch{try{n=require("toml").parse(e)}catch{try{n=require("js-yaml").load(e)}catch(o){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${t} 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 ${t}`)),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 ${t}`),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(e){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${t}:`,e)}}async _expandFileGlobs(t,e,i){for(const[n,o]of Object.entries(e))try{const f=N.join(t,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),p=g.mergeConfigs(i,o);this.fileConfigs.set(l,p),this.debug&&c.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${s}`)}}catch(f){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,f)}}_storeFunctionConfigs(t,e,i){for(const[n,o]of Object.entries(e)){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(t,c));this.functionConfigs.has(l)||this.functionConfigs.set(l,new Map);const p=this.functionConfigs.get(l),d=g.mergeConfigs(i,o);p.set(s,d),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${l}::${s}`)}}async _resolveInheritance(){}_getDirectoryConfig(t){let e=N.dirname(N.normalize(t));const i=[];for(;e&&e!==N.dirname(e);){const n=this.directoryConfigs.get(e);n&&i.unshift(n),e=N.dirname(e)}return i.reduce((n,o)=>g.mergeConfigs(n,o),{})}}const se="__sf_globalConfigLoader";function ae(){return globalThis[se]??null}async function V(r,t){const e=new be(r,t);(function(i){globalThis[se]=i})(e),await e.loadAllConfigs()}function Q(r,t){const e=ae();return e?e.getConfig(r,t):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),g.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 t=process.env.SF_FUNCSPAN_JSONL_FILE;if(t&&r.includes(t))return!0;const e=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!e||!r.includes(e))}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 t=process.env.API_GRAPHQL_ENDPOINT;if(t&&r===new URL(t).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(t){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",t))}if(r.__sf_worker_pool_patched__)return;Object.defineProperty(r,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Y)if(typeof r[t]=="function"){const e=r[t];r[t]=function(...i){return g.isSendingInternalTelemetry()?e.apply(this,i):te(i[0])?e.apply(this,i):typeof i[i.length-1]=="function"?g.captureWorkerPoolOperation("dns",t,e,i,this):e.apply(this,i)},Object.defineProperty(r[t],"name",{value:t,writable:!1})}(function(t){if(!t.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!t.promises.__sf_worker_pool_patched__){Object.defineProperty(t.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Y)if(typeof t.promises[e]=="function"){const i=t.promises[e];t.promises[e]=function(...n){return g.isSendingInternalTelemetry()?i.apply(this,n):te(n[0])?i.apply(this,n):g.captureWorkerPoolPromiseOperation("dns",e,i,n,this)},Object.defineProperty(t.promises[e],"name",{value:e,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,M=!1;function ie(){if(M)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),g.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Z)try{const t=require("node:fs");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Fe)if(typeof t[e]=="function"){const i=t[e];t[e]=function(...n){return De(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("fs",e,i,n,this):i.apply(this,n)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}Z=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(t){console.error("[WorkerPool] Error patching fs module:",t)}})()),g.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),Pe()),g.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ne)try{const t=require("node:crypto");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Ce)if(typeof t[e]=="function"){const i=t[e];t[e]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("crypto",e,i,n,this):i.apply(this,n)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}ne=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(t){console.error("[WorkerPool] Error patching crypto module:",t)}})()),g.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!re)try{const t=require("node:zlib");if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Ne)if(typeof t[e]=="function"){const i=t[e];t[e]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("zlib",e,i,n,this):i.apply(this,n)},Object.defineProperty(t[e],"name",{value:e,writable:!1})}re=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(t){console.error("[WorkerPool] Error patching zlib module:",t)}})()),M=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function oe(){return M}let U=!1,A=!1,q=null;function O(r){const t=a.getGlobalConfigUnsafe(),e=t?.sfDebug||!1;e&&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
|
|
183
|
-
`;
|
|
184
|
-
`)[2]||"",
|
|
181
|
+
`,t=o.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});l.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class we{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)Se.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?l.getEnvConfig():l.getDefaultConfig(),n=this._getDirectoryConfig(e),s=E.normalize(e),p=this.fileConfigs.get(s)||{};let c={};if(t){const a=this.functionConfigs.get(s);a&&(c=a.get(t)||{})}return l.mergeConfigs(i,n,p,c)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=await V.readdir(e,{withFileTypes:!0});for(const n of i){const s=E.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 V.readFile(e,"utf-8"),i=E.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 p=E.join(e,n),c=await ye.glob(p,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${c.length} files`);for(const a of c){const d=E.normalize(a),g=l.mergeConfigs(i,s);this.fileConfigs.set(d,g),this.debug&&c.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${a}`)}}catch(p){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,p)}}_storeFunctionConfigs(e,t,i){for(const[n,s]of Object.entries(t)){const p=n.split("::");if(p.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[c,a]=p,d=E.normalize(E.join(e,c));this.functionConfigs.has(d)||this.functionConfigs.set(d,new Map);const g=this.functionConfigs.get(d),u=l.mergeConfigs(i,s);g.set(a,u),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${d}::${a}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=E.dirname(E.normalize(e));const i=[];for(;t&&t!==E.dirname(t);){const n=this.directoryConfigs.get(t);n&&i.unshift(n),t=E.dirname(t)}return i.reduce((n,s)=>l.mergeConfigs(n,s),{})}}const ue="__sf_globalConfigLoader";function le(){return globalThis[ue]??null}async function Z(r,e){const t=new we(r,e);(function(i){globalThis[ue]=i})(t),await t.loadAllConfigs()}function ee(r,e){const t=le();return t?t.getConfig(r,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),l.getDefaultConfig())}function te(){return le()!==null}const Ee=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],ne=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Pe=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Te=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let re=!1;function ke(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 ie=!1;function oe(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 Oe(){if(!ie)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 ne)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return l.isSendingInternalTelemetry()?t.apply(this,i):oe(i[0])?t.apply(this,i):typeof i[i.length-1]=="function"?l.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 ne)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return l.isSendingInternalTelemetry()?i.apply(this,n):oe(n[0])?i.apply(this,n):l.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),ie=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let se=!1,ae=!1,W=!1;function ce(){if(W)return;const r=process.env.SF_DEBUG==="true";r&&console.log("[WorkerPool] Initializing worker pool patching..."),l.isModuleTrackingEnabled("fs")&&(r&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!re)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 Ee)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return ke(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?l.captureWorkerPoolOperation("fs",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] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),l.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),Oe()),l.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!se)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 Pe)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?l.captureWorkerPoolOperation("crypto",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}se=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),l.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!ae)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 Te)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?l.captureWorkerPoolOperation("zlib",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ae=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),W=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function de(){return W}let x=!1,B=!1,G=null;function U(r){const e=o.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 s=n==="true"||n==="1"?"funcspans.jsonl":n,p=Date.now(),c=process.hrtime.bigint(),a=BigInt(r.startTimeNs),d=Number(c-a)/1e6,g=new Date(p-d).toISOString(),u=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
|
+
`;K.appendFileSync(s,u,"utf-8")}catch(s){console.error("[FuncSpan] Error writing to JSONL file:",s)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(G||(G=new l.FunctionSpanTransmitter),G).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(s){t&&console.error("[FuncSpan] Error sending function span:",s)}}exports.ContextManager=o.ContextManager,exports.getCurrentFunctionSpanId=o.getCurrentFunctionSpanId,exports.runWithContext=o.runWithContext,exports.clearFuncspanOverride=l.clearFuncspanOverride,exports.getDefaultConfig=l.getDefaultConfig,exports.getEnvConfig=l.getEnvConfig,exports.getFuncspanOverride=l.getFuncspanOverride,exports.parseHeaderOverride=l.parseHeaderOverride,exports.setFuncspanOverride=l.setFuncspanOverride,exports.isProductionEnvironment=F.isProductionEnvironment,exports.isRuntimeModeEnabled=F.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=F.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=M.setSkipTypeScriptPlugin,exports.transformFunctionSpans=M.transformFunctionSpans,exports.transformFunctionSpansSync=M.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=o.getConfig();new J(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...s){const p=o.getGlobalConfigUnsafe(),c=p?.sfDebug||!1;c&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const a=(function(m,f){const v=l.getFuncspanOverride();if(v){const h=l.parseHeaderOverride(v);if(h)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${m}::${f}`),h}try{return ee(m,f)}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}:`,a),a.enable_sampling&&a.sample_rate<1&&Math.random()>a.sample_rate)return c&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,s);if(a.sample_rate===0)return c&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,s);c&&console.log(`[FuncSpan] Capturing function span for ${e}`);const d=o.ContextManager.getInstance(),g=d.getCurrentFunctionSpanId(),u=o.v4();d.setCurrentFunctionSpanId(u);const S=process.hrtime.bigint(),b=Date.now();let I=null;a.capture_arguments&&(I={},i.paramNames.forEach((m,f)=>{f<s.length&&(I[m]=s[f])}),I&&a.arg_limit_mb>0&&(I=l.truncateToLimit(I,a.arg_limit_mb)));try{const m=r.apply(this,s);if(m&&typeof m.then=="function")return g?d.setCurrentFunctionSpanId(g):d.clearCurrentFunctionSpanId(),m.then($=>{const _=process.hrtime.bigint(),C=Date.now(),P=Number(_-S);let y=null;return a.capture_return_value&&a.return_limit_mb>0&&(y=l.truncateToLimit($,a.return_limit_mb)),U({functionName:e,filePath:t,metadata:i,args:I,result:y,error:null,duration:C-b,durationNs:P,startTimeNs:S.toString(),async:!0,spanId:u,parentSpanId:g,pid:process.pid,threadId:R.threadId}),$},$=>{const _=process.hrtime.bigint(),C=Date.now(),P=Number(_-S);throw U({functionName:e,filePath:t,metadata:i,args:I,result:null,error:$?.message||String($),duration:C-b,durationNs:P,startTimeNs:S.toString(),async:!0,spanId:u,parentSpanId:g,pid:process.pid,threadId:R.threadId}),$});const f=process.hrtime.bigint(),v=Date.now(),h=Number(f-S);let D=null;return a.capture_return_value&&a.return_limit_mb>0&&(D=l.truncateToLimit(m,a.return_limit_mb)),U({functionName:e,filePath:t,metadata:i,args:I,result:D,error:null,duration:v-b,durationNs:h,startTimeNs:S.toString(),async:!1,spanId:u,parentSpanId:g,pid:process.pid,threadId:R.threadId}),g?d.setCurrentFunctionSpanId(g):d.clearCurrentFunctionSpanId(),m}catch(m){const f=process.hrtime.bigint(),v=Date.now(),h=Number(f-S);throw U({functionName:e,filePath:t,metadata:i,args:I,result:null,error:m?.message||String(m),duration:v-b,durationNs:h,startTimeNs:S.toString(),async:!1,spanId:u,parentSpanId:g,pid:process.pid,threadId:R.threadId}),g?d.setCurrentFunctionSpanId(g):d.clearCurrentFunctionSpanId(),m}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const s in r)r.hasOwnProperty(s)&&(n[s]=r[s]);return n},exports.getGlobalConfig=ee,exports.identify=function(r,e,t,i=!1){const n=o.getConfig();new J(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=Z,exports.initializeWorkerPoolPatching=ce,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=te,exports.isSetupInterceptorsInitialized=function(){return x},exports.isWorkerPoolInitialized=de,exports.setupInterceptors=function(r){if(B)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!x){B=!0,l.registerShutdownHooks();try{let e,t;const i=F.stackToString(new Error().stack);if(i){const c=i.split(`
|
|
184
|
+
`)[2]||"",a=c.match(/\((.+):(\d+):\d+\)/)||c.match(/at (.+):(\d+):\d+/);a&&(e=a[1],t=parseInt(a[2],10))}if(!r||!r.apiKey){const c=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(c)}const{config:n}=o.getOrCreateConfig(r);if(o.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)}te()||Z(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)"):de()||(ce(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const s=new z;s.setServiceUUID(n.serviceUUID),F.initializeLogInterceptor(s),(function(c=[]){const a=new De(c);new _e().doSend(a.getExcludedDomains());const d=new Ce,g=new Fe;a.patchFetch(d,g),a.patchHttp(d,g)})(n.domainsToNotPropagateHeadersTo);const p=new ve;p.setServiceUUID(n.serviceUUID),F.initializeExceptionInterceptor(p),be(),new Ne().send(),x=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{B=!1}}};
|