@sailfish-ai/sf-veritas 0.2.17 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/contextManager-C-sqFxpi.js +267 -0
  2. package/dist/contextManager-wMuxqwl9.cjs +1 -0
  3. package/dist/funcSpanTransformer-D0W2t41q.cjs +1 -0
  4. package/dist/funcSpanTransformer-S_WeAt_m.js +251 -0
  5. package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
  6. package/dist/plugins/funcspanEsbuildPlugin.mjs +2 -2
  7. package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
  8. package/dist/plugins/funcspanRollupPlugin.mjs +2 -2
  9. package/dist/plugins/funcspanTscPlugin.cjs +1 -1
  10. package/dist/plugins/funcspanTscPlugin.mjs +2 -2
  11. package/dist/plugins/funcspanVitePlugin.cjs +1 -1
  12. package/dist/plugins/funcspanVitePlugin.mjs +2 -2
  13. package/dist/plugins/funcspanWebpackLoader.cjs +1 -1
  14. package/dist/plugins/funcspanWebpackLoader.mjs +1 -1
  15. package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
  16. package/dist/plugins/funcspanWebpackPlugin.mjs +1 -1
  17. package/dist/runtimeConfig-B8LSswM8.cjs +9 -0
  18. package/dist/runtimeConfig-GwWjhV9M.js +379 -0
  19. package/dist/sf-veritas.cjs +13 -13
  20. package/dist/sf-veritas.mjs +241 -250
  21. package/dist/types/debuggerWorker.d.ts +2 -2
  22. package/dist/types/generated/worker-data.d.ts +1 -1
  23. package/dist/types/setupConfig.d.ts +5 -0
  24. package/dist/types/utils.d.ts +7 -0
  25. package/dist/worker-pool-capture.cjs +1 -1
  26. package/dist/worker-pool-capture.mjs +1 -1
  27. package/dist/{workerPoolSpanCapture-BUdAamcg.cjs → workerPoolSpanCapture-B3yge78T.cjs} +1 -1
  28. package/dist/{workerPoolSpanCapture-DEW40aIL.js → workerPoolSpanCapture-DqBbNQLv.js} +1 -1
  29. package/package.json +9 -2
  30. package/dist/contextManager-Cx03mw7l.js +0 -258
  31. package/dist/contextManager-CxQqBCEA.cjs +0 -1
  32. package/dist/funcSpanTransformer-Byqzu4B1.js +0 -231
  33. package/dist/funcSpanTransformer-CDh0o-AP.cjs +0 -1
  34. package/dist/runtimeConfig-DndXTWki.js +0 -353
  35. package/dist/runtimeConfig-TWzqPe1S.cjs +0 -8
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./contextManager-CxQqBCEA.cjs"),p=require("./workerPoolSpanCapture-BUdAamcg.cjs"),h=require("./runtimeConfig-TWzqPe1S.cjs"),ae=require("node:module"),x=require("fs"),ce=require("./source-map-rHHEdpre.cjs"),de=require("path"),ue=require("glob"),E=require("worker_threads"),O=require("./funcSpanTransformer-CDh0o-AP.cjs");function ie(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 L=ie(x),F=ie(de);class P extends p.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!c.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){c.getConfig().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./contextManager-wMuxqwl9.cjs"),u=require("./workerPoolSpanCapture-B3yge78T.cjs"),g=require("./runtimeConfig-B8LSswM8.cjs"),ae=require("node:module"),H=require("fs"),ce=require("./source-map-rHHEdpre.cjs"),de=require("fs/promises"),le=require("path"),ue=require("glob"),E=require("worker_threads"),O=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 pe=x(H),W=x(de),F=x(le);class P extends u.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!c.getConfig().serviceIdentificationReceived)try{this.send()}catch(t){c.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!,
@@ -30,11 +30,11 @@
30
30
  serviceDisplayName: $serviceDisplayName,
31
31
  )
32
32
  }
33
- `,t=this.getVariables({serviceIdentifier:c.getConfig().serviceIdentifier,serviceVersion:c.getConfig().serviceVersion,library:c.getConfig().packageLibraryType,version:c.getConfig().version,serviceAdditionalMetadata:c.getConfig().serviceAdditionalMetadata,gitSha:c.getConfig().gitSha||"",gitOrg:c.getConfig().gitOrg||void 0,gitRepo:c.getConfig().gitRepo||void 0,gitProvider:c.getConfig().gitProvider||void 0,serviceDisplayName:c.getConfig().serviceDisplayName||void 0});p.nonBlockingPost(this.endpoint,this.operationName,e,t)}}function le(r){try{return JSON.stringify(r),!0}catch{return!1}}class pe extends p.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e,t,i,n){this.sendAppIdentifier(),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 o=(function(d){const a={},l=[];if(d)for(const[f,m]of Object.entries(d))le(m)?a[f]=m:l.push(f);return{traitsJson:JSON.stringify(a),excludedFields:l}})(t);n=o.traitsJson,s=o.excludedFields}const u=this.getVariables({userId:e,traitsJson:n,excludedFields:s,override:i,library:c.getConfig().packageLibraryType,version:c.getConfig().version});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),u)}getQuery(){return`
33
+ `,t=this.getVariables({serviceIdentifier:c.getConfig().serviceIdentifier,serviceVersion:c.getConfig().serviceVersion,library:c.getConfig().packageLibraryType,version:c.getConfig().version,serviceAdditionalMetadata:c.getConfig().serviceAdditionalMetadata,gitSha:c.getConfig().gitSha||"",gitOrg:c.getConfig().gitOrg||void 0,gitRepo:c.getConfig().gitRepo||void 0,gitProvider:c.getConfig().gitProvider||void 0,serviceDisplayName:c.getConfig().serviceDisplayName||void 0});u.nonBlockingPost(this.endpoint,this.operationName,e,t)}}class ge extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e,t,i,n){this.sendAppIdentifier(),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 o=g.serializeJsonWithExclusions(t);n=o.traitsJson,s=o.excludedFields}const l=this.getVariables({userId:e,traitsJson:n,excludedFields:s,override:i,library:c.getConfig().packageLibraryType,version:c.getConfig().version});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),l)}getQuery(){return`
34
34
  mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
35
35
  ${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
36
36
  }
37
- `}}class W{constructor(e){this.apiKey=e,this.metadataTransmitter=new pe}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"');c.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),c.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class B extends p.BaseTransmitter{serviceIdentifier=new P;constructor(){super()}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),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){c.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
37
+ `}}class K{constructor(e){this.apiKey=e,this.metadataTransmitter=new ge}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"');c.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),c.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,i),this.metadataTransmitter.doSend(e,t,n,i)}}class B extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super()}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),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});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}catch(t){c.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
38
38
  ${this.queryType} ${this.operationName}(
39
39
  $apiKey: String!,
40
40
  $serviceUuid: String!,
@@ -58,7 +58,7 @@
58
58
  sourceLine: $sourceLine
59
59
  )
60
60
  }
61
- `}}class ge extends p.BaseTransmitter{serviceIdentifier=new P;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")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e,t){this.sendAppIdentifier(),this.send(e,t)}async send(e,t){c.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(h.CustomJSONEncoderForFrameInfo.encode(t)),n=this.normalizedSupplementalForGraphQL(),s=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:c.getConfig().packageLibraryType,version:c.getConfig().version,...n});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
61
+ `}}class fe extends u.BaseTransmitter{serviceIdentifier=new P;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")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e,t){this.sendAppIdentifier(),this.send(e,t)}async send(e,t){c.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(g.CustomJSONEncoderForFrameInfo.encode(t)),n=this.normalizedSupplementalForGraphQL(),s=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:c.getConfig().packageLibraryType,version:c.getConfig().version,...n});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
62
62
  mutation ${this.operationName}(
63
63
  $apiKey: String!,
64
64
  $serviceUuid: String!,
@@ -86,7 +86,7 @@
86
86
  parentSpanId: $parentSpanId
87
87
  )
88
88
  }
89
- `}}const K="getting request source code";var w=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(w||{});const U="http:",R="https:",fe=ae.createRequire(require("node:url").pathToFileURL(__filename).href);let j=!1;function he(){const r=c.getConfig().sfDebug;if(j)return void(r&&h.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;j=!0;try{e=fe("node:http"),r&&h.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void h.internalError("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(r&&h.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&&h.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...s){if(n!=="request")return r&&h.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...s);const u=s[0],o=s[1],d=(function(g){const y={};if(!g)return y;for(const[v,_]of Object.entries(g))_!=null&&(Array.isArray(_)?y[v.toLowerCase()]=_.join(", "):y[v.toLowerCase()]=String(_));return y})(u?.headers),a=d["x-sf3-rid"],l=d["x-sf3-functionspancaptureoverride"];r&&(h.internalLog("[patchNodeHttpInbound] Intercepted request event."),h.internalLog("[patchNodeHttpInbound] Inbound headers:",d),h.internalLog("[patchNodeHttpInbound] Trace header:",a),h.internalLog("[patchNodeHttpInbound] FuncSpan override header:",l));const f=c.ContextManager.getInstance();f.setTraceId(a);const m=f.getTraceId();r&&h.internalLog("[patchNodeHttpInbound] Context traceId set:",m);const S=()=>f.runWith({inboundHeaders:d,...a?{traceId:a}:{}},()=>{a&&f.setTraceId(a),r&&h.internalLog("[patchNodeHttpInbound] Running request handler in context.");const g=()=>{r&&h.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",f.getTraceId())};return o.on("finish",g),o.on("close",g),i.call(this,n,u,o)});if(!l)return S();try{return p.funcspanOverrideStorage.run(l,()=>S())}catch{return S()}}):r&&h.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class me extends B{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
89
+ `}}const z="getting request source code";var w=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(w||{});const L="http:",U="https:",he=ae.createRequire(require("node:url").pathToFileURL(__filename).href);let j=!1;function me(){const r=c.getConfig().sfDebug;if(j)return void(r&&g.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;j=!0;try{e=he("node:http"),r&&g.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(n){return void g.internalError("Failed to require node:http:",n)}if(!e?.Server?.prototype)return void(r&&g.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&&g.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(n,...s){if(n!=="request")return r&&g.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...s);const l=s[0],o=s[1],d=(function(f){const m={};if(!f)return m;for(const[v,_]of Object.entries(f))_!=null&&(Array.isArray(_)?m[v.toLowerCase()]=_.join(", "):m[v.toLowerCase()]=String(_));return m})(l?.headers),a=d["x-sf3-rid"],p=d["x-sf3-functionspancaptureoverride"];r&&(g.internalLog("[patchNodeHttpInbound] Intercepted request event."),g.internalLog("[patchNodeHttpInbound] Inbound headers:",d),g.internalLog("[patchNodeHttpInbound] Trace header:",a),g.internalLog("[patchNodeHttpInbound] FuncSpan override header:",p));const h=c.ContextManager.getInstance();h.setTraceId(a);const y=h.getTraceId();r&&g.internalLog("[patchNodeHttpInbound] Context traceId set:",y);const S=()=>h.runWith({inboundHeaders:d,...a?{traceId:a}:{}},()=>{a&&h.setTraceId(a),r&&g.internalLog("[patchNodeHttpInbound] Running request handler in context.");const f=()=>{r&&g.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",h.getTraceId())};return o.on("finish",f),o.on("close",f),i.call(this,n,l,o)});if(!p)return S();try{return u.funcspanOverrideStorage.run(p,()=>S())}catch{return S()}}):r&&g.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class ye extends B{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
90
90
  ${this.queryType} ${this.operationName}(
91
91
  $apiKey: String!,
92
92
  $serviceUuid: String!,
@@ -98,7 +98,7 @@
98
98
  domains: $domains
99
99
  )
100
100
  }
101
- `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};p.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class ye extends p.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const{name:t,column:i,line:n,entrypoint:s,retryWithoutTraceId:u}=e,o=this.getVariables({name:t,column:i,line:n,entrypoint:s,retryWithoutTraceId:u});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}getQuery(){return`
101
+ `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};u.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class Se extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const{name:t,column:i,line:n,entrypoint:s,retryWithoutTraceId:l}=e,o=this.getVariables({name:t,column:i,line:n,entrypoint:s,retryWithoutTraceId:l});u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}getQuery(){return`
102
102
  mutation ${this.operationName}(
103
103
  $apiKey: String!,
104
104
  $sessionId: String!,
@@ -122,15 +122,15 @@
122
122
  ${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
123
123
  )
124
124
  }
125
- `}}class Se extends p.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}getQuery(){return`
125
+ `}}class Ie extends u.BaseTransmitter{serviceIdentifier=new P;constructor(){super(),this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}getQuery(){return`
126
126
  mutation ${this.operationName}(
127
127
  $data: NetworkRequestInput!
128
128
  ) {
129
129
  ${this.queryName}(
130
130
  data: $data)
131
131
  }
132
- `}async send(e){const t={data:{...e}};await p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const k=[400,403];class Ie{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=c.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),c.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[u,o]of Object.entries(e))if(u.toLowerCase()===s){i=o;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 u=JSON.parse(x.readFileSync(s,"utf-8"));let o=(await new ce.sourceMapExports.SourceMapConsumer(u)).originalPositionFor({line:t,column:i});o.source&&(n=o)}catch(u){c.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,u)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=c.getConfig().sfDebug?10:t,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,n);const u=new Error(K);K in Error&&Error.captureStackTrace(u,this.captureFirstUserLines);const o=u.stack||"";Error.stackTraceLimit=s;const d=o.split(`
133
- `).slice(1),a=[];for(const l of d)if(!(l.includes("node:internal")||l.includes("internal/modules")||l.includes("internal/process")||l.includes("node_modules")||l.includes(".next/server/chunks")||l.includes("RequestInterceptor")||l.includes("contextManager")||l.includes("setupConfig"))&&(a.push(l.trim()),a.length>=t))break;for(const l of a){const f=this.parseStackFrame(l);f?(async()=>{const{originalPos:m}=await this.getOriginalPosition(f.filePath,f.line,f.column);if(m){c.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",m);const S={line:m.line?.toString()||w.UNKNOWN,column:m.column?.toString()||w.NOT_CAPTURED,name:m.name||w.NOT_CAPTURED,entrypoint:m.source,retryWithoutTraceId:i};e.doSend(S)}})():c.getConfig().sfDebug&&console.error("Could not parse stack line:",l)}}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!c.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):c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(e,t){const i=p.getFuncspanOverride();if(i){const o=p.parseHeaderOverride(i);if(o&&o.sample_rate===0)return void(c.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(),u=c.v4();e.set(this.HEADER_TRACING,`${n}/${s}/${u}`),c.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 u=new Headers(s?.headers);if(u.get(this.HEADER_LOG_GUARD)==="true"||u.get(this.HEADER_PRINT_GUARD)==="true"||u.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,s);this.captureFirstUserLines(e);const o=Date.now();let d;typeof n=="string"||n instanceof URL?d=n.toString():n instanceof Request?(d=n.url,n.headers.forEach((g,y)=>{u.set(y,g)})):c.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",d);const a=new URL(d).hostname,l=new Headers(u),f=this.addTracingHeaders(u,d),m={...s,headers:u};let S;try{let g=!1;this.addTracingHeaders(l,d),S=await i(d,m),f&&k.includes(S.status)?(S=await i(d,{...s,headers:l}),g=!0,this.captureFirstUserLines(e,10,g)):this.contextManager.addSupportedDomains(a);const y=Date.now();c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${d}, Status: ${S.status}, Duration: ${y-o}ms`);const{sessionId:v,pageVisitId:_,requestId:N}=this.extractIdsFromTraceHeader(u),$=c.getConfig(),b={apiKey:$.apiKey,requestId:N,pageVisitId:_,recordingSessionId:v,serviceUuid:$.serviceUUID,timestampStart:o.toString(),timestampEnd:y.toString(),responseCode:S.status,success:!0,error:null,url:d,method:m.method||"GET",retryWithoutTraceId:g,parentSpanId:c.getCurrentFunctionSpanId()};if($.captureRequestHeaders){const I={};u.forEach((C,D)=>{I[D]=C}),b.requestHeaders=I}if($.captureResponseHeaders){const I={};S.headers.forEach((C,D)=>{I[D]=C}),b.responseHeaders=I}if($.captureRequestBody&&s?.body)try{const I=typeof s.body=="string"?s.body:JSON.stringify(s.body);b.requestBody=I.length>$.requestBodyLimitBytes?I.substring(0,$.requestBodyLimitBytes)+"...[truncated]":I}catch{}if($.captureResponseBody)try{const I=S.clone(),C=await I.text();b.responseBody=C.length>$.responseBodyLimitBytes?C.substring(0,$.responseBodyLimitBytes)+"...[truncated]":C}catch{}return t.doSend(b),S}catch(g){const y=Date.now();c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${d}, Error: ${g}, Duration: ${y-o}ms`)}}:c.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!h.https||typeof h.https.request!="function")return void(c.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=h.https.request.bind(h.https),n=h.https.request.bind(h.https);h.https.request=function(s,u){let o;try{if(typeof s=="string"){const a=new URL(s);o={protocol:a.protocol||U,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else s instanceof URL?o={protocol:s.protocol||U,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(o={...s},o.protocol||(o.protocol=U));if(o.headers){const a=`${o.protocol}//${o.hostname}`;this.addTracingHeaders(o.headers,a),this.captureFirstUserLines(e)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",a),a}let d=!1;return i(o,a=>{const l=`${o.protocol}//${o.hostname}`;if(o.headers&&this.shouldPropagateHeaders(new URL(l).hostname)&&k.includes(a.statusCode||0)){o.hostname;const g={...o,headers:{...o.headers}};delete g.headers[this.HEADER_TRACING],i(g,u),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:S}=this.extractIdsFromTraceHeader(o.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:S,pageVisitId:m,recordingSessionId:f,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:l,method:o.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),u?.(a)})},h.https.request=function(s,u){let o;try{if(typeof s=="string"){const a=new URL(s);o={protocol:a.protocol||R,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else s instanceof URL?o={protocol:s.protocol||R,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(o={...s},o.protocol||(o.protocol=R));if(o.headers){const a=`${o.protocol}//${o.hostname}`;this.addTracingHeaders(o.headers,a)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",a),a}let d=!1;return n(o,a=>{const l=`${o.protocol}//${o.hostname}`;if(o.headers&&this.shouldPropagateHeaders(new URL(l).hostname)&&k.includes(a.statusCode||0)){const g={...o,headers:{...o.headers}};delete g.headers[this.HEADER_TRACING],n(g,u),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:S}=this.extractIdsFromTraceHeader(o.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:S,pageVisitId:m,recordingSessionId:f,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:l,method:o.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),u?.(a)})},c.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e()}catch{}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class ve extends B{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const e=`
132
+ `}async send(e){const t={data:{...e}};await u.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const R=[400,403];class ve{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=c.ContextManager.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),c.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[l,o]of Object.entries(e))if(l.toLowerCase()===s){i=o;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 l=JSON.parse(H.readFileSync(s,"utf-8"));let o=(await new ce.sourceMapExports.SourceMapConsumer(l)).originalPositionFor({line:t,column:i});o.source&&(n=o)}catch(l){c.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,l)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=c.getConfig().sfDebug?10:t,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,n);const l=new Error(z);z in Error&&Error.captureStackTrace(l,this.captureFirstUserLines);const o=g.stackToString(l.stack);Error.stackTraceLimit=s;const d=o.split(`
133
+ `).slice(1),a=[];for(const p of d)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"))&&(a.push(p.trim()),a.length>=t))break;for(const p of a){const h=this.parseStackFrame(p);h?(async()=>{const{originalPos:y}=await this.getOriginalPosition(h.filePath,h.line,h.column);if(y){c.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",y);const S={line:y.line?.toString()||w.UNKNOWN,column:y.column?.toString()||w.NOT_CAPTURED,name:y.name||w.NOT_CAPTURED,entrypoint:y.source,retryWithoutTraceId:i};e.doSend(S)}})():c.getConfig().sfDebug&&console.error("Could not parse stack line:",p)}}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!c.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):c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),n}addTracingHeader(e,t){const i=u.getFuncspanOverride();if(i){const o=u.parseHeaderOverride(i);if(o&&o.sample_rate===0)return void(c.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(),l=c.v4();e.set(this.HEADER_TRACING,`${n}/${s}/${l}`),c.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 l=new Headers(s?.headers);if(l.get(this.HEADER_LOG_GUARD)==="true"||l.get(this.HEADER_PRINT_GUARD)==="true"||l.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(n,s);this.captureFirstUserLines(e);const o=Date.now();let d;typeof n=="string"||n instanceof URL?d=n.toString():n instanceof Request?(d=n.url,n.headers.forEach((f,m)=>{l.set(m,f)})):c.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),c.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",d);const a=new URL(d).hostname,p=new Headers(l),h=this.addTracingHeaders(l,d),y={...s,headers:l};let S;try{let f=!1;this.addTracingHeaders(p,d),S=await i(d,y),h&&R.includes(S.status)?(S=await i(d,{...s,headers:p}),f=!0,this.captureFirstUserLines(e,10,f)):this.contextManager.addSupportedDomains(a);const m=Date.now();c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${d}, Status: ${S.status}, Duration: ${m-o}ms`);const{sessionId:v,pageVisitId:_,requestId:N}=this.extractIdsFromTraceHeader(l),$=c.getConfig(),b={apiKey:$.apiKey,requestId:N,pageVisitId:_,recordingSessionId:v,serviceUuid:$.serviceUUID,timestampStart:o.toString(),timestampEnd:m.toString(),responseCode:S.status,success:!0,error:null,url:d,method:y.method||"GET",retryWithoutTraceId:f,parentSpanId:c.getCurrentFunctionSpanId()};if($.captureRequestHeaders){const I={};l.forEach((C,D)=>{I[D]=C}),b.requestHeaders=I}if($.captureResponseHeaders){const I={};S.headers.forEach((C,D)=>{I[D]=C}),b.responseHeaders=I}if($.captureRequestBody&&s?.body)try{const I=typeof s.body=="string"?s.body:JSON.stringify(s.body);b.requestBody=I.length>$.requestBodyLimitBytes?I.substring(0,$.requestBodyLimitBytes)+"...[truncated]":I}catch{}if($.captureResponseBody)try{const I=S.clone(),C=await I.text();b.responseBody=C.length>$.responseBodyLimitBytes?C.substring(0,$.responseBodyLimitBytes)+"...[truncated]":C}catch{}return t.doSend(b),S}catch(f){const m=Date.now();c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${d}, Error: ${f}, Duration: ${m-o}ms`)}}:c.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(c.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!g.https||typeof g.https.request!="function")return void(c.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=g.https.request.bind(g.https),n=g.https.request.bind(g.https);g.https.request=function(s,l){let o;try{if(typeof s=="string"){const a=new URL(s);o={protocol:a.protocol||L,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else s instanceof URL?o={protocol:s.protocol||L,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(o={...s},o.protocol||(o.protocol=L));if(o.headers){const a=`${o.protocol}//${o.hostname}`;this.addTracingHeaders(o.headers,a),this.captureFirstUserLines(e)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",a),a}let d=!1;return i(o,a=>{const p=`${o.protocol}//${o.hostname}`;if(o.headers&&this.shouldPropagateHeaders(new URL(p).hostname)&&R.includes(a.statusCode||0)){o.hostname;const f={...o,headers:{...o.headers}};delete f.headers[this.HEADER_TRACING],i(f,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:h,pageVisitId:y,requestId:S}=this.extractIdsFromTraceHeader(o.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:S,pageVisitId:y,recordingSessionId:h,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:p,method:o.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},g.https.request=function(s,l){let o;try{if(typeof s=="string"){const a=new URL(s);o={protocol:a.protocol||U,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else s instanceof URL?o={protocol:s.protocol||U,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(o={...s},o.protocol||(o.protocol=U));if(o.headers){const a=`${o.protocol}//${o.hostname}`;this.addTracingHeaders(o.headers,a)}else c.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(a){throw c.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",a),a}let d=!1;return n(o,a=>{const p=`${o.protocol}//${o.hostname}`;if(o.headers&&this.shouldPropagateHeaders(new URL(p).hostname)&&R.includes(a.statusCode||0)){const f={...o,headers:{...o.headers}};delete f.headers[this.HEADER_TRACING],n(f,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:h,pageVisitId:y,requestId:S}=this.extractIdsFromTraceHeader(o.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:S,pageVisitId:y,recordingSessionId:h,serviceUuid:c.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:a.statusCode||0,success:!!a.statusCode&&a.statusCode<400,error:null,url:p,method:o.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},c.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request 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.sendAppIdentifier(),this.send()}async send(){const e=`
134
134
  ${this.queryType} ${this.operationName}(
135
135
  $apiKey: String!,
136
136
  $serviceUuid: String!,
@@ -166,7 +166,7 @@
166
166
  setupInterceptorsLine: $setupInterceptorsLine,
167
167
  )
168
168
  }
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});p.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)L.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),s=F.normalize(e),u=this.fileConfigs.get(s)||{};let o={};if(t){const d=this.functionConfigs.get(s);d&&(o=d.get(t)||{})}return p.mergeConfigs(i,n,u,o)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=L.readdirSync(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=L.readFileSync(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 u=F.join(e,n),o=await ue.glob(u,{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),l=p.mergeConfigs(i,s);this.fileConfigs.set(a,l),this.debug&&o.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${d}`)}}catch(u){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,u)}}_storeFunctionConfigs(e,t,i){for(const[n,s]of Object.entries(t)){const u=n.split("::");if(u.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);continue}const[o,d]=u,a=F.normalize(F.join(e,o));this.functionConfigs.has(a)||this.functionConfigs.set(a,new Map);const l=this.functionConfigs.get(a),f=p.mergeConfigs(i,s);l.set(d,f),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)=>p.mergeConfigs(n,s),{})}}const oe="__sf_globalConfigLoader";function se(){return globalThis[oe]??null}async function z(r,e){const t=new _e(r,e);(function(i){globalThis[oe]=i})(t),await t.loadAllConfigs()}function J(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)"),p.getDefaultConfig())}function V(){return se()!==null}const $e=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Q=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],be=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ce=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let X=!1;function Fe(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 Y=!1;function Z(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 Ne(){if(!Y)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 Q)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return p.isSendingInternalTelemetry()?t.apply(this,i):Z(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 Q)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return p.isSendingInternalTelemetry()?i.apply(this,n):Z(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),Y=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let ee=!1,te=!1,H=!1;function ne(){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(!X)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 $e)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return Fe(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})}X=!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..."),Ne()),p.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ee)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 be)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})}ee=!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(!te)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 Ce)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})}te=!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 re(){return H}let q=!1,A=!1,M=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 s=n==="true"||n==="1"?"funcspans.jsonl":n,u=Date.now(),o=process.hrtime.bigint(),d=BigInt(r.startTimeNs),a=Number(o-d)/1e6,l=new Date(u-a).toISOString(),f=JSON.stringify({timestamp:l,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})+`
171
- `;x.appendFileSync(s,f,"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{(M||(M=new p.FunctionSpanTransmitter),M).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(s){t&&console.error("[FuncSpan] Error sending function span:",s)}}exports.ContextManager=c.ContextManager,exports.getCurrentFunctionSpanId=c.getCurrentFunctionSpanId,exports.runWithContext=c.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=h.isProductionEnvironment,exports.isRuntimeModeEnabled=h.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=h.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=O.setSkipTypeScriptPlugin,exports.transformFunctionSpans=O.transformFunctionSpans,exports.transformFunctionSpansSync=O.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=c.getConfig();new W(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...s){const u=c.getGlobalConfigUnsafe(),o=u?.sfDebug||!1;o&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const d=(function(y,v){const _=p.getFuncspanOverride();if(_){const N=p.parseHeaderOverride(_);if(N)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${y}::${v}`),N}try{return J(y,v)}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(o&&console.log(`[FuncSpan] Config for ${t}::${e}:`,d),d.enable_sampling&&d.sample_rate<1&&Math.random()>d.sample_rate)return o&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,s);if(d.sample_rate===0)return o&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,s);o&&console.log(`[FuncSpan] Capturing function span for ${e}`);const a=c.ContextManager.getInstance(),l=a.getCurrentFunctionSpanId(),f=c.v4();a.setCurrentFunctionSpanId(f);const m=process.hrtime.bigint(),S=Date.now();let g=null;d.capture_arguments&&(g={},i.paramNames.forEach((y,v)=>{v<s.length&&(g[y]=s[v])}),g&&d.arg_limit_mb>0&&(g=p.truncateToLimit(g,d.arg_limit_mb)));try{const y=r.apply(this,s);if(y&&typeof y.then=="function")return l?a.setCurrentFunctionSpanId(l):a.clearCurrentFunctionSpanId(),y.then(b=>{const I=process.hrtime.bigint(),C=Date.now(),D=Number(I-m);let G=null;return d.capture_return_value&&d.return_limit_mb>0&&(G=p.truncateToLimit(b,d.return_limit_mb)),T({functionName:e,filePath:t,metadata:i,args:g,result:G,error:null,duration:C-S,durationNs:D,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:l,pid:process.pid,threadId:E.threadId}),b},b=>{const I=process.hrtime.bigint(),C=Date.now(),D=Number(I-m);throw T({functionName:e,filePath:t,metadata:i,args:g,result:null,error:b?.message||String(b),duration:C-S,durationNs:D,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:l,pid:process.pid,threadId:E.threadId}),b});const v=process.hrtime.bigint(),_=Date.now(),N=Number(v-m);let $=null;return d.capture_return_value&&d.return_limit_mb>0&&($=p.truncateToLimit(y,d.return_limit_mb)),T({functionName:e,filePath:t,metadata:i,args:g,result:$,error:null,duration:_-S,durationNs:N,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:l,pid:process.pid,threadId:E.threadId}),l?a.setCurrentFunctionSpanId(l):a.clearCurrentFunctionSpanId(),y}catch(y){const v=process.hrtime.bigint(),_=Date.now(),N=Number(v-m);throw T({functionName:e,filePath:t,metadata:i,args:g,result:null,error:y?.message||String(y),duration:_-S,durationNs:N,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:l,pid:process.pid,threadId:E.threadId}),l?a.setCurrentFunctionSpanId(l):a.clearCurrentFunctionSpanId(),y}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const s in r)r.hasOwnProperty(s)&&(n[s]=r[s]);return n},exports.getGlobalConfig=J,exports.identify=function(r,e,t,i=!1){const n=c.getConfig();new W(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=z,exports.initializeWorkerPoolPatching=ne,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=V,exports.isSetupInterceptorsInitialized=function(){return q},exports.isWorkerPoolInitialized=re,exports.setupInterceptors=function(r){if(A)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!q){A=!0;try{let e,t;const i=new Error().stack;if(i){const o=i.split(`
172
- `)[2]||"",d=o.match(/\((.+):(\d+):\d+\)/)||o.match(/at (.+):(\d+):\d+/);d&&(e=d[1],t=parseInt(d[2],10))}if(!r||!r.apiKey){const o=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(o)}const{config:n}=c.getOrCreateConfig(r);if(e&&(n.setupInterceptorsFile=e),t&&(n.setupInterceptorsLine=t),n.sfDebug&&console.log("Updated configuration after applying options:",n),!n.apiKey||!n.apiGraphqlEndpoint){const o=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(o),new Error(o)}V()||z(void 0,n.sfDebug).catch(o=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",o)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):re()||(ne(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const s=new B;s.setServiceUUID(n.serviceUUID),h.initializeLogInterceptor(s),(function(o=[]){const d=new Ie(o);new me().doSend(d.getExcludedDomains());const a=new ye,l=new Se;d.patchFetch(a,l),d.patchHttp(a,l)})(n.domainsToNotPropagateHeadersTo);const u=new ge;u.setServiceUUID(n.serviceUUID),h.initializeExceptionInterceptor(u),he(),new ve().send(),q=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{A=!1}}};
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 s=n==="true"||n==="1"?"funcspans.jsonl":n,l=Date.now(),o=process.hrtime.bigint(),d=BigInt(r.startTimeNs),a=Number(o-d)/1e6,p=new Date(l-a).toISOString(),h=JSON.stringify({timestamp:p,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})+`
171
+ `;H.appendFileSync(s,h,"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{(A||(A=new u.FunctionSpanTransmitter),A).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(s){t&&console.error("[FuncSpan] Error sending function span:",s)}}exports.ContextManager=c.ContextManager,exports.getCurrentFunctionSpanId=c.getCurrentFunctionSpanId,exports.runWithContext=c.runWithContext,exports.clearFuncspanOverride=u.clearFuncspanOverride,exports.getDefaultConfig=u.getDefaultConfig,exports.getEnvConfig=u.getEnvConfig,exports.getFuncspanOverride=u.getFuncspanOverride,exports.parseHeaderOverride=u.parseHeaderOverride,exports.setFuncspanOverride=u.setFuncspanOverride,exports.isProductionEnvironment=g.isProductionEnvironment,exports.isRuntimeModeEnabled=g.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=g.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=O.setSkipTypeScriptPlugin,exports.transformFunctionSpans=O.transformFunctionSpans,exports.transformFunctionSpansSync=O.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=c.getConfig();new K(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...s){const l=c.getGlobalConfigUnsafe(),o=l?.sfDebug||!1;o&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const d=(function(m,v){const _=u.getFuncspanOverride();if(_){const N=u.parseHeaderOverride(_);if(N)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${m}::${v}`),N}try{return V(m,v)}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(o&&console.log(`[FuncSpan] Config for ${t}::${e}:`,d),d.enable_sampling&&d.sample_rate<1&&Math.random()>d.sample_rate)return o&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,s);if(d.sample_rate===0)return o&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,s);o&&console.log(`[FuncSpan] Capturing function span for ${e}`);const a=c.ContextManager.getInstance(),p=a.getCurrentFunctionSpanId(),h=c.v4();a.setCurrentFunctionSpanId(h);const y=process.hrtime.bigint(),S=Date.now();let f=null;d.capture_arguments&&(f={},i.paramNames.forEach((m,v)=>{v<s.length&&(f[m]=s[v])}),f&&d.arg_limit_mb>0&&(f=u.truncateToLimit(f,d.arg_limit_mb)));try{const m=r.apply(this,s);if(m&&typeof m.then=="function")return p?a.setCurrentFunctionSpanId(p):a.clearCurrentFunctionSpanId(),m.then(b=>{const I=process.hrtime.bigint(),C=Date.now(),D=Number(I-y);let G=null;return d.capture_return_value&&d.return_limit_mb>0&&(G=u.truncateToLimit(b,d.return_limit_mb)),T({functionName:e,filePath:t,metadata:i,args:f,result:G,error:null,duration:C-S,durationNs:D,startTimeNs:y.toString(),async:!0,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),b},b=>{const I=process.hrtime.bigint(),C=Date.now(),D=Number(I-y);throw T({functionName:e,filePath:t,metadata:i,args:f,result:null,error:b?.message||String(b),duration:C-S,durationNs:D,startTimeNs:y.toString(),async:!0,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),b});const v=process.hrtime.bigint(),_=Date.now(),N=Number(v-y);let $=null;return d.capture_return_value&&d.return_limit_mb>0&&($=u.truncateToLimit(m,d.return_limit_mb)),T({functionName:e,filePath:t,metadata:i,args:f,result:$,error:null,duration:_-S,durationNs:N,startTimeNs:y.toString(),async:!1,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),p?a.setCurrentFunctionSpanId(p):a.clearCurrentFunctionSpanId(),m}catch(m){const v=process.hrtime.bigint(),_=Date.now(),N=Number(v-y);throw T({functionName:e,filePath:t,metadata:i,args:f,result:null,error:m?.message||String(m),duration:_-S,durationNs:N,startTimeNs:y.toString(),async:!1,spanId:h,parentSpanId:p,pid:process.pid,threadId:E.threadId}),p?a.setCurrentFunctionSpanId(p):a.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=V,exports.identify=function(r,e,t,i=!1){const n=c.getConfig();new K(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=J,exports.initializeWorkerPoolPatching=re,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=Q,exports.isSetupInterceptorsInitialized=function(){return k},exports.isWorkerPoolInitialized=ie,exports.setupInterceptors=function(r){if(q)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!k){q=!0;try{let e,t;const i=g.stackToString(new Error().stack);if(i){const o=i.split(`
172
+ `)[2]||"",d=o.match(/\((.+):(\d+):\d+\)/)||o.match(/at (.+):(\d+):\d+/);d&&(e=d[1],t=parseInt(d[2],10))}if(!r||!r.apiKey){const o=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(o)}const{config:n}=c.getOrCreateConfig(r);if(c.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 o=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(o),new Error(o)}Q()||J(void 0,n.sfDebug).catch(o=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",o)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):ie()||(re(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const s=new B;s.setServiceUUID(n.serviceUUID),g.initializeLogInterceptor(s),(function(o=[]){const d=new ve(o);new ye().doSend(d.getExcludedDomains());const a=new Se,p=new Ie;d.patchFetch(a,p),d.patchHttp(a,p)})(n.domainsToNotPropagateHeadersTo);const l=new fe;l.setServiceUUID(n.serviceUUID),g.initializeExceptionInterceptor(l),me(),new _e().send(),k=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{q=!1}}};