@sailfish-ai/sf-veritas 0.3.1 → 0.3.2

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.
@@ -1,4 +1,4 @@
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=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./contextManager-qXvO_a5y.cjs"),g=require("./workerPoolSpanCapture-BUFN_RMW.cjs"),F=require("./runtimeConfig-C4_zc4Zg.cjs"),ye=require("node:module"),z=require("fs"),P=require("http"),k=require("https"),Se=require("./source-map-rHHEdpre.cjs"),Ie=require("fs/promises"),ve=require("path"),$e=require("glob"),O=require("worker_threads"),A=require("./funcSpanTransformer-D0W2t41q.cjs");function V(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 be=V(z),Q=V(Ie),E=V(ve);class R extends g.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
- `,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`
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});g.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class _e extends g.BaseTransmitter{serviceIdentifier=new R;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 a=[];if(!n){const d=F.serializeJsonWithExclusions(t);n=d.traitsJson,a=d.excludedFields}const p=this.getVariables({userId:e,traitsJson:n,excludedFields:a,override:i,library:o.getConfig().packageLibraryType,version:o.getConfig().version});g.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 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`
43
+ `}}class X{constructor(e){this.apiKey=e,this.metadataTransmitter=new _e}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 J extends g.BaseTransmitter{serviceIdentifier=new R;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});g.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 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`
67
+ `}}class Ce extends g.BaseTransmitter{serviceIdentifier=new R;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(),a=this.getVariables({exceptionMessage:e,traceJson:i,reentrancyGuardPreactive:!1,library:o.getConfig().packageLibraryType,version:o.getConfig().version,...n});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),a)}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 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=`
95
+ `}}const Y="X-Sf4-Prid",Z="getting request source code";var L=(r=>(r.UNKNOWN="unknown",r.ANONYMOUS="anonymous",r.NOT_CAPTURED="not captured",r))(L||{});const ee="http:",Fe=ye.createRequire(require("node:url").pathToFileURL(__filename).href);let te=!1;function we(){const r=o.getConfig().sfDebug;if(te)return void(r&&F.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;te=!0;try{e=Fe("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,...a){if(n!=="request")return r&&F.internalLog(`[patchNodeHttpInbound] Passing through event: ${n}`),i.call(this,n,...a);const p=a[0],d=a[1],s=(function(I){const h={};if(!I)return h;for(const[f,$]of Object.entries(I))$!=null&&(Array.isArray($)?h[f.toLowerCase()]=$.join(", "):h[f.toLowerCase()]=String($));return h})(p?.headers),u=s["x-sf3-rid"],l=s["x-sf3-functionspancaptureoverride"];r&&(F.internalLog("[patchNodeHttpInbound] Intercepted request event."),F.internalLog("[patchNodeHttpInbound] Inbound headers:",s),F.internalLog("[patchNodeHttpInbound] Trace header:",u),F.internalLog("[patchNodeHttpInbound] FuncSpan override header:",l));const c=o.ContextManager.getInstance();c.setTraceId(u);const y=c.getTraceId();r&&F.internalLog("[patchNodeHttpInbound] Context traceId set:",y);const v=()=>c.runWith({inboundHeaders:s,...u?{traceId:u}:{}},()=>{u&&c.setTraceId(u),r&&F.internalLog("[patchNodeHttpInbound] Running request handler in context.");const I=()=>{r&&F.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",c.getTraceId())};return d.on("finish",I),d.on("close",I),i.call(this,n,p,d)});if(!l)return v();try{return g.funcspanOverrideStorage.run(l,()=>v())}catch{return v()}}):r&&F.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}const ne=new Map;function H(r,e){const t=`${r}|${e}`;let i=ne.get(t);return i||(i=new RegExp(r,e),ne.set(t,i)),i}function M(r,e){let t,i;if(typeof r=="string"?t=r:typeof URL<"u"&&r instanceof URL?t=r.href:typeof Request<"u"&&r instanceof Request?t=r.url:r!=null&&typeof r.toString=="function"&&(t=r.toString()),!t)return!1;try{i=new URL(t,"http://localhost/")}catch{return!1}const{hostname:n,pathname:a,port:p,protocol:d}=i;if(!/^https?:$/.test(d))return!1;const s=n.startsWith("www.")?n.slice(4).toLowerCase():n.toLowerCase();return e.some(u=>{const l=String(u||"").replace(/^[a-zA-Z]+:\/\//,"");if(!l)return!1;let[c,y]=l.split("/",2),v="";c.includes(":")&&([c,v]=c.split(":"));const I=H(`^${c.replace(/\./g,"\\.").replace(/\*/g,".*")}$`,"i"),h=s.startsWith("www.")?s.slice(4):s;if(v&&p!==v)return!1;if(c.startsWith("*.")){const f=c.slice(2).toLowerCase();return s===f||h===f||s.endsWith("."+f)?y?H(`^/${y.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(a):!0:!1}return!I.test(h)&&!I.test(s)?!1:y?H(`^/${y.replace(/\*/g,".*").replace(/\/$/,"")}`,"i").test(a):!0})}class De extends J{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: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`
107
+ `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};g.nonBlockingPost(this.endpoint,this.operationName,t,i)}}class Ne extends g.BaseTransmitter{serviceIdentifier=new R;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:a,retryWithoutTraceId:p}=e,d=this.getVariables({name:t,column:i,line:n,entrypoint:a,retryWithoutTraceId:p});g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),d)}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 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`
131
+ `}}class Ee extends g.BaseTransmitter{serviceIdentifier=new R;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(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=`
138
+ `}async send(e){const t={data:{...e}};await g.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const B=[400,403];function x(r,e){return e!=="none"&&(e==="all"||r==="GET"||r==="HEAD"||r==="OPTIONS")}class Te{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 a=t.toLowerCase();for(const[p,d]of Object.entries(e))if(p.toLowerCase()===a){i=d;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,a]=t;return{filePath:i,line:parseInt(n,10),column:parseInt(a,10)}}async getOriginalPosition(e,t,i){let n={source:e,line:t,column:i,name:null};if(e.includes("://"))return{originalPos:n};const a=e+".map";try{const p=JSON.parse(z.readFileSync(a,"utf-8"));let d=(await new Se.sourceMapExports.SourceMapConsumer(p)).originalPositionFor({line:t,column:i});d.source&&(n=d)}catch(p){o.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${a}:`,p)}return{originalPos:n}}captureFirstUserLines(e,t=10,i=!1){const n=o.getConfig().sfDebug?10:t,a=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(a,n);const p=new Error(Z);Z in Error&&Error.captureStackTrace(p,this.captureFirstUserLines);const d=F.stackToString(p.stack);Error.stackTraceLimit=a;const s=d.split(`
139
+ `).slice(1),u=[];for(const l of s)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"))&&(u.push(l.trim()),u.length>=t))break;for(const l of u){const c=this.parseStackFrame(l);c?(async()=>{const{originalPos:y}=await this.getOriginalPosition(c.filePath,c.line,c.column);if(y){o.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",y);const v={line:y.line?.toString()||L.UNKNOWN,column:y.column?.toString()||L.NOT_CAPTURED,name:y.name||L.NOT_CAPTURED,entrypoint:y.source,retryWithoutTraceId:i};e.doSend(v)}})():o.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){const t=o.getConfig(),i=t.domainsToPropagateHeadersTo,n=t.domainsToNotPropagateHeadersTo||[],a=Array.from(o.DEFAULT_DOMAINS_TO_EXCLUDE);return!!M(e,i)&&!(n.length>0&&M(e,n))&&!M(e,a)}addTracingHeaders(e,t){const i=this.shouldPropagateHeaders(t);if(i)this.addTracingHeader(e,t);else if(o.getConfig().sfDebug){let n=t;try{n=new URL(t).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${n}`)}return i}deriveTraceBaseAndParent(e){const t=e.split("/").filter(Boolean);return t.length<2?{base:e,parent:e}:{base:`${t[0]}/${t[1]}`,parent:e}}addTracingHeader(e,t){const i=g.getFuncspanOverride();if(i){const s=g.parseHeaderOverride(i);if(s&&s.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(),{base:a,parent:p}=this.deriveTraceBaseAndParent(n),d=o.v4();e.set(this.HEADER_TRACING,`${a}/${d}`),e.set(Y,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,a)=>{const p=new Headers(a?.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,a);this.captureFirstUserLines(e);const d=Date.now();let s,u="GET";if(typeof n=="string"||n instanceof URL)s=n.toString(),u=(a?.method||"GET").toUpperCase();else{if(!(n instanceof Request))return o.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),i(n,a);s=n.url,u=n.method.toUpperCase(),n.headers.forEach((m,w)=>{p.set(w,m)})}o.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",s);let l="unknown";try{l=new URL(s).hostname}catch{return o.getConfig().sfDebug&&console.warn(`[RequestInterceptor] Could not parse URL '${s}' — passing through without tracing headers.`),i(n,a)}const c=new Headers(p),y=this.addTracingHeaders(p,s),v=m=>n instanceof Request?[new Request(n,{...a||{},headers:m}),void 0]:[s,{...a,headers:m}],I=o.getConfig().retryOnClientError;let h,f=!1;try{const[m,w]=v(p);if(h=await i(m,w),y&&x(u,I)&&B.includes(h.status)){const[b,_]=v(c);h=await i(b,_),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(l)}catch(b){o.getConfig().sfDebug&&console.error("[RequestInterceptor] addSupportedDomains failed:",b)}}catch(m){const w=Date.now();o.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${s}, Error: ${m}, Duration: ${w-d}ms`);try{const{sessionId:b,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(p),T=o.getConfig();t.doSend({apiKey:T.apiKey,requestId:C,pageVisitId:_,recordingSessionId:b,serviceUuid:T.serviceUUID,timestampStart:d.toString(),timestampEnd:w.toString(),responseCode:0,success:!1,error:m instanceof Error?m.message:typeof m=="string"?m:JSON.stringify(m),url:s,method:u,retryWithoutTraceId:f,parentSpanId:o.getCurrentFunctionSpanId()})}catch(b){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error telemetry send failed:",b)}throw m}const $=Date.now();try{o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${s}, Status: ${h.status}, Duration: ${$-d}ms`);const{sessionId:m,pageVisitId:w,requestId:b}=this.extractIdsFromTraceHeader(p),_=o.getConfig(),C={apiKey:_.apiKey,requestId:b,pageVisitId:w,recordingSessionId:m,serviceUuid:_.serviceUUID,timestampStart:d.toString(),timestampEnd:$.toString(),responseCode:h.status,success:!0,error:null,url:s,method:u,retryWithoutTraceId:f,parentSpanId:o.getCurrentFunctionSpanId()};if(_.captureRequestHeaders){const S={};p.forEach((N,D)=>{S[D]=N}),C.requestHeaders=S}if(_.captureResponseHeaders){const S={};h.headers.forEach((N,D)=>{S[D]=N}),C.responseHeaders=S}if(_.captureRequestBody&&a?.body){const S=a.body,N=_.requestBodyLimitBytes;try{if(typeof S=="string")C.requestBody=S.length>N?S.substring(0,N)+"...[truncated]":S;else if(S instanceof URLSearchParams){const D=S.toString();C.requestBody=D.length>N?D.substring(0,N)+"...[truncated]":D}else if(typeof ArrayBuffer<"u"&&(S instanceof ArrayBuffer||ArrayBuffer.isView(S))){const D=S.byteLength??S.byteLength;C.requestBody=`[binary body, ${D} bytes — not captured]`}else if(typeof Blob<"u"&&S instanceof Blob)C.requestBody=`[Blob, ${S.size} bytes, type=${S.type||"unknown"} — not captured]`;else if(typeof FormData<"u"&&S instanceof FormData)C.requestBody="[FormData — not captured]";else if(typeof ReadableStream<"u"&&S instanceof ReadableStream)C.requestBody="[ReadableStream — not captured]";else{const D=JSON.stringify(S);D&&D!=="{}"&&(C.requestBody=D.length>N?D.substring(0,N)+"...[truncated]":D)}}catch{}}let T;if(_.captureResponseBody){const S=(h.headers.get("content-type")||"").toLowerCase();if(!S||S.includes("json")||S.includes("xml")||S.includes("text/")||S.includes("javascript")||S.includes("ecmascript")||S.includes("x-www-form-urlencoded")||S.includes("application/graphql")){const N=h.clone(),D=_.responseBodyLimitBytes;T=(async()=>{try{const q=await N.text(),me=q.length>D?q.substring(0,D)+"...[truncated]":q;try{t.doSend({...C,responseBody:me})}catch{}}catch{}})(),T.catch(()=>{})}else C.responseBody=`[non-text body, content-type=${S} — not captured]`}T||t.doSend(C)}catch(m){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):",m)}return h}: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=this.shouldPropagateHeaders(t);if(i){const n=g.getFuncspanOverride();if(n){const u=g.parseHeaderOverride(n);if(u&&u.sample_rate===0)return o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`),!1}const a=this.contextManager.getOrSetSfTraceId(),{base:p,parent:d}=this.deriveTraceBaseAndParent(a),s=o.v4();e[this.HEADER_TRACING]=`${p}/${s}`,e[Y]=d,o.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}else if(o.getConfig().sfDebug){let n=t;try{n=new URL(t).hostname}catch{}console.error(`[RequestInterceptor] Excluded domain: ${n}`)}return i}patchHttp(e,t){if(o.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!P||typeof P.request!="function")return void(o.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=P.request.bind(P),n=k.request.bind(k),a=(s,u,l,c=ee)=>{let y,v;if(typeof s=="string"||s instanceof URL){const I=typeof s=="string"?new URL(s):s;y={...typeof u=="object"&&u!==null?u:{},protocol:I.protocol||c,hostname:I.hostname,port:I.port||void 0,path:I.pathname+I.search},v=typeof u=="function"?u:l}else y={...s},y.protocol||(y.protocol=c),v=typeof u=="function"?u:void 0;return y.headers||(y.headers={}),[y,v]},p=(s,u,l)=>{const[c,y]=a(s,u,l,ee);try{const f=`${c.protocol}//${c.hostname}`;this.addTracingHeadersToPlainObject(c.headers,f),this.captureFirstUserLines(e)}catch(f){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",f)}const v=(c.method||"GET").toUpperCase(),I=o.getConfig().retryOnClientError,h=(f,$,m)=>{try{const{sessionId:w,pageVisitId:b,requestId:_}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:_,pageVisitId:b,recordingSessionId:w,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:$,method:v,retryWithoutTraceId:m,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}y?.(f)};return i(c,f=>{const $=`${c.protocol}//${c.hostname}`;let m=!1;try{m=this.shouldPropagateHeaders($)}catch{m=!1}if(m&&x(v,I)&&B.includes(f.statusCode||0)){f.resume();try{const{sessionId:b,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:C,pageVisitId:_,recordingSessionId:b,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!1,error:null,url:$,method:v,retryWithoutTraceId:!1,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(e,10,!0)}catch{}const w={...c,headers:{...c.headers}};return delete w.headers[this.HEADER_TRACING],void i(w,b=>{h(b,$,!0)}).end()}h(f,$,!1)})},d=(s,u,l)=>{const[c,y]=a(s,u,l,"https:");try{const f=`${c.protocol}//${c.hostname}`;this.addTracingHeadersToPlainObject(c.headers,f),this.captureFirstUserLines(e)}catch(f){o.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",f)}const v=(c.method||"GET").toUpperCase(),I=o.getConfig().retryOnClientError,h=(f,$,m)=>{try{const{sessionId:w,pageVisitId:b,requestId:_}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:_,pageVisitId:b,recordingSessionId:w,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:$,method:v,retryWithoutTraceId:m,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}y?.(f)};return n(c,f=>{const $=`${c.protocol}//${c.hostname}`;let m=!1;try{m=this.shouldPropagateHeaders($)}catch{m=!1}if(m&&x(v,I)&&B.includes(f.statusCode||0)){f.resume();try{const{sessionId:b,pageVisitId:_,requestId:C}=this.extractIdsFromTraceHeader(c.headers);t.doSend({apiKey:o.getConfig().apiKey,requestId:C,pageVisitId:_,recordingSessionId:b,serviceUuid:o.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:f.statusCode||0,success:!1,error:null,url:$,method:v,retryWithoutTraceId:!1,parentSpanId:o.getCurrentFunctionSpanId()})}catch{}try{this.captureFirstUserLines(e,10,!0)}catch{}const w={...c,headers:{...c.headers}};return delete w.headers[this.HEADER_TRACING],void n(w,b=>{h(b,$,!0)}).end()}h(f,$,!1)})};P.request=p,k.request=d,P.get=(s,u,l)=>{const c=p(s,u,l);return c.end(),c},k.get=(s,u,l)=>{const c=d(s,u,l);return c.end(),c},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 Pe extends J{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
- `,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}}};
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});g.nonBlockingPost(this.endpoint,this.operationName,e,i)}}class Re{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)be.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?g.getEnvConfig():g.getDefaultConfig(),n=this._getDirectoryConfig(e),a=E.normalize(e),p=this.fileConfigs.get(a)||{};let d={};if(t){const s=this.functionConfigs.get(a);s&&(d=s.get(t)||{})}return g.mergeConfigs(i,n,p,d)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const i=await Q.readdir(e,{withFileTypes:!0});for(const n of i){const a=E.join(e,n.name);n.isFile()&&n.name===".sailfish"?t.push(a):n.name==="node_modules"||n.isDirectory()&&n.name.startsWith(".")&&n.name!==".sailfish"||n.isDirectory()&&await this._walkDirectory(a,t)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const t=await Q.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(a){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON, TOML, or YAML:`,a))}}}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,a]of Object.entries(t))try{const p=E.join(e,n),d=await $e.glob(p,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${d.length} files`);for(const s of d){const u=E.normalize(s),l=g.mergeConfigs(i,a);this.fileConfigs.set(u,l),this.debug&&d.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${s}`)}}catch(p){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`,p)}}_storeFunctionConfigs(e,t,i){for(const[n,a]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[d,s]=p,u=E.normalize(E.join(e,d));this.functionConfigs.has(u)||this.functionConfigs.set(u,new Map);const l=this.functionConfigs.get(u),c=g.mergeConfigs(i,a);l.set(s,c),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${u}::${s}`)}}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,a)=>g.mergeConfigs(n,a),{})}}const fe="__sf_globalConfigLoader";function he(){return globalThis[fe]??null}async function re(r,e){const t=new Re(r,e);(function(i){globalThis[fe]=i})(t),await t.loadAllConfigs()}function ie(r,e){const t=he();return t?t.getConfig(r,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"),g.getDefaultConfig())}function oe(){return he()!==null}const ke=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],se=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Oe=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ue=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let ae=!1;function Le(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 ce=!1;function de(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 qe(){if(!ce)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 se)if(typeof r[e]=="function"){const t=r[e];r[e]=function(...i){return g.isSendingInternalTelemetry()?t.apply(this,i):de(i[0])?t.apply(this,i):typeof i[i.length-1]=="function"?g.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 se)if(typeof e.promises[t]=="function"){const i=e.promises[t];e.promises[t]=function(...n){return g.isSendingInternalTelemetry()?i.apply(this,n):de(n[0])?i.apply(this,n):g.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),ce=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(r){console.error("[WorkerPool] Error patching dns module:",r)}}let ue=!1,le=!1,j=!1;function pe(){if(j)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(!ae)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 ke)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return Le(n[0])?i.apply(this,n):typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("fs",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] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),g.isModuleTrackingEnabled("dns")&&(r&&console.log("[WorkerPool] Patching dns module..."),qe()),g.isModuleTrackingEnabled("crypto")&&(r&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ue)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 Oe)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("crypto",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}ue=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),g.isModuleTrackingEnabled("zlib")&&(r&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!le)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 Ue)if(typeof e[t]=="function"){const i=e[t];e[t]=function(...n){return typeof n[n.length-1]=="function"?g.captureWorkerPoolOperation("zlib",t,i,n,this):i.apply(this,n)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}le=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),j=!0,r&&console.log("[WorkerPool] Worker pool patching initialized")}function ge(){return j}let W=!1,G=!1,K=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 a=n==="true"||n==="1"?"funcspans.jsonl":n,p=Date.now(),d=process.hrtime.bigint(),s=BigInt(r.startTimeNs),u=Number(d-s)/1e6,l=new Date(p-u).toISOString(),c=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})+`
183
+ `;z.appendFileSync(a,c,"utf-8")}catch(a){console.error("[FuncSpan] Error writing to JSONL file:",a)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(K||(K=new g.FunctionSpanTransmitter),K).send([i]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(a){t&&console.error("[FuncSpan] Error sending function span:",a)}}exports.ContextManager=o.ContextManager,exports.getCurrentFunctionSpanId=o.getCurrentFunctionSpanId,exports.runWithContext=o.runWithContext,exports.clearFuncspanOverride=g.clearFuncspanOverride,exports.getDefaultConfig=g.getDefaultConfig,exports.getEnvConfig=g.getEnvConfig,exports.getFuncspanOverride=g.getFuncspanOverride,exports.parseHeaderOverride=g.parseHeaderOverride,exports.setFuncspanOverride=g.setFuncspanOverride,exports.isProductionEnvironment=F.isProductionEnvironment,exports.isRuntimeModeEnabled=F.isRuntimeModeEnabled,exports.shouldEnableRuntimeHooks=F.shouldEnableRuntimeHooks,exports.setSkipTypeScriptPlugin=A.setSkipTypeScriptPlugin,exports.transformFunctionSpans=A.transformFunctionSpans,exports.transformFunctionSpansSync=A.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(r,e={},t,i=!1){const n=o.getConfig();new X(n.apiKey).addOrUpdateMetadata(r,e,t,i)},exports.captureFunctionSpan=function(r,e,t,i){const n=function(...a){const p=o.getGlobalConfigUnsafe(),d=p?.sfDebug||!1;d&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const s=(function(h,f){const $=g.getFuncspanOverride();if($){const m=g.parseHeaderOverride($);if(m)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${h}::${f}`),m}try{return ie(h,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(d&&console.log(`[FuncSpan] Config for ${t}::${e}:`,s),s.enable_sampling&&s.sample_rate<1&&Math.random()>s.sample_rate)return d&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),r.apply(this,a);if(s.sample_rate===0)return d&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),r.apply(this,a);d&&console.log(`[FuncSpan] Capturing function span for ${e}`);const u=o.ContextManager.getInstance(),l=u.getCurrentFunctionSpanId(),c=o.v4();u.setCurrentFunctionSpanId(c);const y=process.hrtime.bigint(),v=Date.now();let I=null;s.capture_arguments&&(I={},i.paramNames.forEach((h,f)=>{f<a.length&&(I[h]=a[f])}),I&&s.arg_limit_mb>0&&(I=g.truncateToLimit(I,s.arg_limit_mb)));try{const h=r.apply(this,a);if(h&&typeof h.then=="function")return l?u.setCurrentFunctionSpanId(l):u.clearCurrentFunctionSpanId(),h.then(b=>{const _=process.hrtime.bigint(),C=Date.now(),T=Number(_-y);let S=null;return s.capture_return_value&&s.return_limit_mb>0&&(S=g.truncateToLimit(b,s.return_limit_mb)),U({functionName:e,filePath:t,metadata:i,args:I,result:S,error:null,duration:C-v,durationNs:T,startTimeNs:y.toString(),async:!0,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),b},b=>{const _=process.hrtime.bigint(),C=Date.now(),T=Number(_-y);throw U({functionName:e,filePath:t,metadata:i,args:I,result:null,error:b?.message||String(b),duration:C-v,durationNs:T,startTimeNs:y.toString(),async:!0,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),b});const f=process.hrtime.bigint(),$=Date.now(),m=Number(f-y);let w=null;return s.capture_return_value&&s.return_limit_mb>0&&(w=g.truncateToLimit(h,s.return_limit_mb)),U({functionName:e,filePath:t,metadata:i,args:I,result:w,error:null,duration:$-v,durationNs:m,startTimeNs:y.toString(),async:!1,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),l?u.setCurrentFunctionSpanId(l):u.clearCurrentFunctionSpanId(),h}catch(h){const f=process.hrtime.bigint(),$=Date.now(),m=Number(f-y);throw U({functionName:e,filePath:t,metadata:i,args:I,result:null,error:h?.message||String(h),duration:$-v,durationNs:m,startTimeNs:y.toString(),async:!1,spanId:c,parentSpanId:l,pid:process.pid,threadId:O.threadId}),l?u.setCurrentFunctionSpanId(l):u.clearCurrentFunctionSpanId(),h}};Object.defineProperty(n,"name",{value:e,writable:!1});for(const a in r)r.hasOwnProperty(a)&&(n[a]=r[a]);return n},exports.getGlobalConfig=ie,exports.identify=function(r,e,t,i=!1){const n=o.getConfig();new X(n.apiKey).identify(r,e,t,i)},exports.initializeConfigLoader=re,exports.initializeWorkerPoolPatching=pe,exports.isAlreadyInstrumented=function(r){return!!r.includes("captureFunctionSpan(")||!!r.includes("@sailfish-ai/sf-veritas")||!(!r.includes("/* @sailfish-instrumented */")&&!r.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=oe,exports.isSetupInterceptorsInitialized=function(){return W},exports.isWorkerPoolInitialized=ge,exports.setupInterceptors=function(r){if(G)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!W){G=!0,g.registerShutdownHooks();try{let e,t;const i=F.stackToString(new Error().stack);if(i){const d=i.split(`
184
+ `)[2]||"",s=d.match(/\((.+):(\d+):\d+\)/)||d.match(/at (.+):(\d+):\d+/);s&&(e=s[1],t=parseInt(s[2],10))}if(!r||!r.apiKey){const d=`The required API Key is not provided: ${JSON.stringify(r)}`;console.error(d)}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 d=`The required config is not provided: ${JSON.stringify(n)}`;throw console.error(d),new Error(d)}oe()||re(void 0,n.sfDebug).catch(d=>{n.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",d)}),process.env.SF_WORKER_POOL_DISABLED==="true"?n.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):ge()||(pe(),n.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const a=new J;a.setServiceUUID(n.serviceUUID),F.initializeLogInterceptor(a),(function(d=[]){const s=new Te(d);new De().doSend(s.getExcludedDomains());const u=new Ne,l=new Ee;s.patchFetch(u,l),s.patchHttp(u,l)})(n.domainsToNotPropagateHeadersTo);const p=new Ce;p.setServiceUUID(n.serviceUUID),F.initializeExceptionInterceptor(p),we(),new Pe().send(),W=!0,n.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{G=!1}}};