@sailfish-ai/sf-veritas 0.2.13 → 0.2.16

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 (33) hide show
  1. package/dist/contextManager-Cx03mw7l.js +258 -0
  2. package/dist/contextManager-CxQqBCEA.cjs +1 -0
  3. package/dist/funcSpanTransformer-Byqzu4B1.js +231 -0
  4. package/dist/funcSpanTransformer-CDh0o-AP.cjs +1 -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-CgLfwL3X.js → runtimeConfig-DndXTWki.js} +130 -127
  18. package/dist/{runtimeConfig-DIsq-KCn.cjs → runtimeConfig-TWzqPe1S.cjs} +7 -7
  19. package/dist/sf-veritas.cjs +37 -12
  20. package/dist/sf-veritas.mjs +574 -509
  21. package/dist/types/funcSpanConfig.d.ts +0 -4
  22. package/dist/types/funcSpanConfigLoader.d.ts +1 -1
  23. package/dist/types/networkRequestTransmitter.d.ts +4 -0
  24. package/dist/types/setupConfig.d.ts +35 -0
  25. package/dist/worker-pool-capture.cjs +1 -1
  26. package/dist/worker-pool-capture.mjs +1 -1
  27. package/dist/{workerPoolSpanCapture-D85i6nhQ.cjs → workerPoolSpanCapture-COwiNikM.cjs} +2 -2
  28. package/dist/{workerPoolSpanCapture-BYaf3NOr.js → workerPoolSpanCapture-d-8ExI18.js} +84 -82
  29. package/package.json +2 -1
  30. package/dist/contextManager-BkETRITg.cjs +0 -1
  31. package/dist/contextManager-CEPhVu9T.js +0 -197
  32. package/dist/funcSpanTransformer-B9WWl-g1.cjs +0 -1
  33. package/dist/funcSpanTransformer-CWNEWRxq.js +0 -225
@@ -1,8 +1,8 @@
1
- "use strict";const O=require("fs"),D=require("./source-map-rHHEdpre.cjs"),M=require("worker_threads"),d=require("./contextManager-BkETRITg.cjs"),P=require("path"),F={};class N{file;line;function;code;locals;offender;column;constructor({file:g,line:C,function:c,code:A,locals:i={},offender:n=!1,column:l}){this.file=g,this.line=C,this.function=c,this.code=A,this.locals=i,this.offender=n,this.column=l}toDict(){const g={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([C,c])=>[C,String(c)]))};return this.offender&&(g.offender=this.offender),this.column!==void 0&&(g.column=this.column),g}toJson(){return JSON.stringify(this.toDict())}}class H{static encode(g){return g instanceof N?g.toDict():Array.isArray(g)?g.map(C=>H.encode(C)):typeof g=="object"&&g!==null?JSON.stringify(g):g}static stringify(g){return JSON.stringify(H.encode(g),(C,c)=>c instanceof N?c.toDict():c)}}const _=["/sf-veritas/","/@sailfish-ai/","/node_modules/","/dist/","/<","/internal/","node:"],h=new Map;function q(I){return _.some(g=>I.includes(g))}function $(I){let g=I;g.startsWith("file://")&&(g=g.substring(7)),process.platform==="win32"&&g.startsWith("/")&&g.length>2&&g[2]===":"&&(g=g.substring(1));try{return P.resolve(g)}catch{return I}}function gg(I=0){const g=new Error().stack;if(!g)return[null,null];const C=(function(l,e){const o=2+e;return l.split(`
1
+ "use strict";const O=require("fs"),D=require("os"),M=require("./source-map-rHHEdpre.cjs"),P=require("worker_threads"),d=require("./contextManager-CxQqBCEA.cjs"),_=require("path"),E={};class N{file;line;function;code;locals;offender;column;constructor({file:I,line:C,function:c,code:e,locals:i={},offender:l=!1,column:n}){this.file=I,this.line=C,this.function=c,this.code=e,this.locals=i,this.offender=l,this.column=n}toDict(){const I={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([C,c])=>[C,String(c)]))};return this.offender&&(I.offender=this.offender),this.column!==void 0&&(I.column=this.column),I}toJson(){return JSON.stringify(this.toDict())}}class H{static encode(I){return I instanceof N?I.toDict():Array.isArray(I)?I.map(C=>H.encode(C)):typeof I=="object"&&I!==null?JSON.stringify(I):I}static stringify(I){return JSON.stringify(H.encode(I),(C,c)=>c instanceof N?c.toDict():c)}}const q=["/sf-veritas/","/@sailfish-ai/","/node_modules/","/dist/","/<","/internal/","node:"],h=new Map;function $(g){return q.some(I=>g.includes(I))}function II(g){let I=g;I.startsWith("file://")&&(I=I.substring(7)),process.platform==="win32"&&I.startsWith("/")&&I.length>2&&I[2]===":"&&(I=I.substring(1));try{return _.resolve(I)}catch{return g}}function gI(g=0){const I=new Error().stack;if(!I)return[null,null];const C=(function(n,A){const o=2+A;return n.split(`
2
2
  `).slice(o,o+5).join(`
3
- `)})(g,I),c=h.get(C);if(c)return c;const A=(function(l){if(!l)return[];const e=l.split(`
4
- `).slice(1),o=[];for(const t of e){let Z=/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/.exec(t);Z?o.push({functionName:Z[1],file:Z[2],line:parseInt(Z[3],10),column:parseInt(Z[4],10)}):(Z=/at\s+(.+?):(\d+):(\d+)/.exec(t),Z&&o.push({functionName:"<anonymous>",file:Z[1],line:parseInt(Z[2],10),column:parseInt(Z[3],10)}))}return o})(g),i=1+I;for(let l=i;l<Math.min(A.length,i+10);l++){const e=A[l];if(!e||!e.file||q(e.file))continue;const o=[$(e.file),e.line];if(h.size>=512){const t=h.keys().next().value;t!==void 0&&h.delete(t)}return h.set(C,o),o}const n=[null,null];return h.set(C,n),n}const f=console.log.bind(console),S=console.error.bind(console),z=console.warn.bind(console),R=console.info.bind(console),k=console.debug.bind(console),W=f,w=S;let B=!1,y,X=0;function L(I){return I=(I=(I=I.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function Ig(I,g,C){const c=(function(i){i.startsWith("at ")&&(i=i.slice(3).trim());const n=i.match(/^(.*?)(:\d+)+(\.map)?$/);return n?n[1]:i})(I);if(!c||c==="<unknown>")return null;const A=c+".map";try{const i=O.readFileSync(A,"utf-8");if(i){const n=JSON.parse(i);let l=new D.sourceMapExports.SourceMapConsumer(n).originalPositionFor({line:g,column:C});if(c&&l.source){const e=L(c),o=n.sources.findIndex(t=>L(t)===e);if(o===-1)d.getConfig().sfDebug&&W(`Source file "${c}" not found in the source map.`);else{const t=n.sourcesContent[o],Z=n.names.join(",");if(t)return{content:t.split(`
5
- `).slice(l.line-1,l.line+20).join(`
6
- `),name:Z,file:l.source};d.getConfig().sfDebug&&W(`No source content available for file "${c}".`)}}return{content:n.sourcesContent[0],name:n.names[0],file:n.file}}}catch(i){d.getConfig().sfDebug&&W(`Cant read/parse "${A}: Error - ".`,i)}return null}function Cg(I){return I?.split("/").pop()||"<unknown>"}function j(I,g){if(!I||typeof I!="object")return!1;for(const C of Object.values(I))if(typeof C=="string"&&C.includes(g)||typeof C=="object"&&j(C,g))return!0;return!1}let p,J,x=!1;function T(I){if(!I)return;const g=I.toLowerCase().trim();return!!["1","true","yes","on"].includes(g)||!["0","false","no","off"].includes(g)&&void 0}function Q(){if(y!==void 0)return y;const I=process.env||{},g=T(I.SF_IS_LOCAL);if(g!==void 0)return y=g;const C=(I.SF_ENV||I.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(C))return y=!0;if(["KUBERNETES_SERVICE_HOST","AWS_EXECUTION_ENV","ECS_CONTAINER_METADATA_URI","ECS_CONTAINER_METADATA_URI_V4","GAE_ENV","K_SERVICE","GOOGLE_CLOUD_PROJECT","WEBSITE_INSTANCE_ID","VERCEL","NETLIFY","DYNO","RENDER","FLY_APP_NAME","RAILWAY_STATIC_URL","CF_PAGES","CLOUDFLARE"].some(A=>!!I[A]))return y=!1;const c=(F.hostname?.()||I.HOSTNAME||"").toLowerCase();return y=!(c!=="localhost"&&!c.endsWith(".local")&&!c.includes("local"))}function K(I,g,C){return new Promise(c=>{try{const A=new URL(I),i=(A.protocol,F).request({method:"GET",hostname:A.hostname,port:A.port||(A.protocol==="https:"?443:80),path:A.pathname+(A.search||""),headers:g},n=>{n.resume(),n.statusCode&&n.statusCode>=200&&n.statusCode<400?c("ok"):c("http_error")});i.on("error",()=>c("error")),i.setTimeout(C,()=>{i.destroy(),c("timeout")}),i.end()}catch{c("error")}})}function U(){if(p!==void 0)return p;const I=process.env.SF_FUNCSPAN_RUNTIME_ENABLED;if(I==="true"||I==="1")return p=!0,!0;if(I==="false"||I==="0")return p=!1,!1;try{const{isRuntimeModeConfigured:g}=require("../funcSpanConfigLoader");if(g&&g())return p=!0,!0}catch{}return p=!1,!1}function E(){return J!==void 0||(J=!Q()),J}exports.CustomJSONEncoderForFrameInfo=H,exports.https=F,exports.initializeExceptionInterceptor=function(I){d.getConfig().sfDebug&&W("Initializing Exception Interceptor...");try{const l=Q();I?.setSupplementalFields?.({isFromLocalService:l}),(async function(e){if(x)return;x=!0;const o=process.env||{};if(T(o.SF_IS_LOCAL)===void 0)try{await(async function(t){const Z=K("http://169.254.169.254/latest/meta-data/",{},t),Y=K("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},t),m=K("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},t);return(await Promise.allSettled([Z,Y,m])).some(s=>s.status==="fulfilled"&&(s.value==="ok"||s.value==="http_error"))})(150)&&y&&(y=!1,e?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(I).catch(()=>{})}catch{}const g=new M.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhc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mJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHsgc2NyaXB0U291cmNlIH0gPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgIkRlYnVnZ2VyLmdldFNjcmlwdFNvdXJjZSIsCiAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2Fscyw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gY2F0Y2ggKGVycikgewogICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBsb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+IHsKICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlcjoiLCBlcnJvcik7CiAgfQp9KTsKCi8vIEtlZXAgdGhlIHdvcmtlciBhbGl2ZQpzZXRJbnRlcnZhbCgoKSA9PiB7fSwgMTAwMDApOwo="),{workerData:{captureAllExceptions:!0}});let C=null;const c=new WeakMap;g.on("message",l=>{if(typeof l=="string"&&d.getConfig().sfDebug&&W(`[Worker] ${l}`),l.readyToGetParameters&&g.postMessage({sfDebug:d.getConfig().sfDebug,stackDepthLocals:d.getConfig().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:d.getConfig().nodeModulesToCollectLocalVariablesOn}),l.type==="exception"){const{frames:e}=l,o=C;if(!o)return;const t=c.get(o),Z=(function(m){return m?m.split(`
7
- `).slice(1).map(s=>{const V=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(s)||/at (.+):(\d+):(\d+)/.exec(s);if(V){const[,u,r,G,b]=V;return new N({function:u||"<anonymous>",locals:{},file:r||"<unknown>",line:parseInt(G,10)||0,code:"<not captured>",column:parseInt(b)||0})}return new N({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(o.stack),Y=(function(m,s){const V=[];let u=-1,r=-1;for(let G=0;G<m.length;G++){const b=Cg(m[G].file);if(r=G,b!=="<unknown>"){for(let a=0;a<s.length;a++){const v=s[a];if(j(v,b)||typeof v.file=="string"&&v.file.includes(b)){u=a,X=0,d.getConfig().sfDebug&&W(`✅ Matched Frame Found: ${b} @ Debugger Frame ${a}`);break}}if(u!==-1)break}}if(u===-1)return X===10?(X=0,m):(++X,d.getConfig().sfDebug&&W(`"❌ No matching frame found. Checking once again, Attempt N ${X}"`),[]);d.getConfig().sfDebug&&W(`🔄 Merging from matched index ${u} onward...`);for(let G=0;G<s.length;G++){const b=m[r+G],a=s[u+G];V.push(new N({function:a?.function||b?.function||"<anonymous>",locals:a?.locals||b?.locals||{},file:b?.file||a?.file||"<unknown>",line:a?.line||b?.line||0,code:a?.code||b?.code||"<not captured>"}))}return V})(Z,e||[]);if(Y.length!==0){C=null;const m=d.getConfig().stackDepthCodeTraceDepth,s=m===-1?Y:Y.slice(0,m+1),V=Math.min(s.length,Z.length);for(let b=0;b<V;b++)(async()=>{const a=Ig(s[b].file,Z[b].line,Z[b].column);a&&(a.content!=null&&(s[b].code=a.content),a.file!=null&&(s[b].file=a.file))})();I.setOperationName("CollectExceptions");const u=o.message?`${o.name}: ${o.message}`:o.name;d.getConfig().sfDebug&&W("error message is : ",u);const r=d.ContextManager.getInstance(),G=c.get(o);G?(r.setTraceIdFor(G,G),r.runWithSession(G,()=>{r.setTraceId(G),I.doSend(u,s)})):I.doSend(u,s),t?d.ContextManager.getInstance().runWithSession(t,()=>{I.doSend(u,s)}):I.doSend(u,s)}}}),g.on("error",l=>{w("[Worker Error]",l)}),g.on("exit",l=>{w(`[Worker] Exited with code ${l}`)}),g.unref();const A=Error,i=new Set;function n(...l){const e=Reflect.construct(A,l);Reflect.setPrototypeOf(e,n.prototype);try{const t=d.ContextManager.getInstance().getTraceId();c.set(e,t)}catch{}A.captureStackTrace&&A.captureStackTrace(e,n);const o=`${e.message}:${e.stack?.split(`
8
- `)[1]?.trim()}`;if(!i.has(o)){i.add(o),C=e;const t=d.ContextManager.getInstance().getTraceId();c.set(e,t),g.postMessage({type:"processException",error:e.message})}return e}n.prototype=Object.create(A.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(n,A),globalThis.Error=n},exports.initializeLogInterceptor=function(I){function g(C,c){const[A,i]=gg(2);I.setOperationName("CollectLogs"),I.doSend([c,C,A,i])}console.log=(...C)=>{if(B)f(...C);else{B=!0;try{g("INFO",C.join(" ")),f(...C)}finally{B=!1}}},console.error=(...C)=>{if(B)S(...C);else{B=!0;try{g("ERROR",C.join(" ")),S(...C)}finally{B=!1}}},console.warn=(...C)=>{if(B)z(...C);else{B=!0;try{g("WARN",C.join(" ")),z(...C)}finally{B=!1}}},console.info=(...C)=>{if(B)R(...C);else{B=!0;try{g("INFO",C.join(" ")),R(...C)}finally{B=!1}}},d.getConfig().logLevel==="DEBUG"&&(console.debug=(...C)=>{if(B)k(...C);else{B=!0;try{g("DEBUG",C.join(" ")),k(...C)}finally{B=!1}}})},exports.internalError=w,exports.internalLog=W,exports.isProductionEnvironment=E,exports.isRuntimeModeEnabled=U,exports.shouldEnableRuntimeHooks=function(){return!!U()&&(!E()||(console.warn("[FuncSpan Runtime] DISABLED in production environment"),!1))};
3
+ `)})(I,g),c=h.get(C);if(c)return c;const e=(function(n){if(!n)return[];const A=n.split(`
4
+ `).slice(1),o=[];for(const t of A){let Z=/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/.exec(t);Z?o.push({functionName:Z[1],file:Z[2],line:parseInt(Z[3],10),column:parseInt(Z[4],10)}):(Z=/at\s+(.+?):(\d+):(\d+)/.exec(t),Z&&o.push({functionName:"<anonymous>",file:Z[1],line:parseInt(Z[2],10),column:parseInt(Z[3],10)}))}return o})(I),i=1+g;for(let n=i;n<Math.min(e.length,i+10);n++){const A=e[n];if(!A||!A.file||$(A.file))continue;const o=[II(A.file),A.line];if(h.size>=512){const t=h.keys().next().value;t!==void 0&&h.delete(t)}return h.set(C,o),o}const l=[null,null];return h.set(C,l),l}const K=console.log.bind(console),S=console.error.bind(console),F=console.warn.bind(console),R=console.info.bind(console),z=console.debug.bind(console),W=K,f=S;let B=!1,y,X=0;function k(g){return g=(g=(g=g.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function CI(g,I,C){const c=(function(i){i.startsWith("at ")&&(i=i.slice(3).trim());const l=i.match(/^(.*?)(:\d+)+(\.map)?$/);return l?l[1]:i})(g);if(!c||c==="<unknown>")return null;const e=c+".map";try{const i=O.readFileSync(e,"utf-8");if(i){const l=JSON.parse(i);let n=new M.sourceMapExports.SourceMapConsumer(l).originalPositionFor({line:I,column:C});if(c&&n.source){const A=k(c),o=l.sources.findIndex(t=>k(t)===A);if(o===-1)d.getConfig().sfDebug&&W(`Source file "${c}" not found in the source map.`);else{const t=l.sourcesContent[o],Z=l.names.join(",");if(t)return{content:t.split(`
5
+ `).slice(n.line-1,n.line+20).join(`
6
+ `),name:Z,file:n.source};d.getConfig().sfDebug&&W(`No source content available for file "${c}".`)}}return{content:l.sourcesContent[0],name:l.names[0],file:l.file}}}catch(i){d.getConfig().sfDebug&&W(`Cant read/parse "${e}: Error - ".`,i)}return null}function cI(g){return g?.split("/").pop()||"<unknown>"}function j(g,I){if(!g||typeof g!="object")return!1;for(const C of Object.values(g))if(typeof C=="string"&&C.includes(I)||typeof C=="object"&&j(C,I))return!0;return!1}let p,J,L=!1;function T(g){if(!g)return;const I=g.toLowerCase().trim();return!!["1","true","yes","on"].includes(I)||!["0","false","no","off"].includes(I)&&void 0}function Q(){if(y!==void 0)return y;const g=process.env||{},I=T(g.SF_IS_LOCAL);if(I!==void 0)return y=I;const C=(g.SF_ENV||g.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(C))return y=!0;if(["KUBERNETES_SERVICE_HOST","AWS_EXECUTION_ENV","ECS_CONTAINER_METADATA_URI","ECS_CONTAINER_METADATA_URI_V4","GAE_ENV","K_SERVICE","GOOGLE_CLOUD_PROJECT","WEBSITE_INSTANCE_ID","VERCEL","NETLIFY","DYNO","RENDER","FLY_APP_NAME","RAILWAY_STATIC_URL","CF_PAGES","CLOUDFLARE"].some(e=>!!g[e]))return y=!1;const c=(D.hostname?.()||g.HOSTNAME||"").toLowerCase();return y=!(c!=="localhost"&&!c.endsWith(".local")&&!c.includes("local"))}function w(g,I,C){return new Promise(c=>{try{const e=new URL(g),i=(e.protocol,E).request({method:"GET",hostname:e.hostname,port:e.port||(e.protocol==="https:"?443:80),path:e.pathname+(e.search||""),headers:I},l=>{l.resume(),l.statusCode&&l.statusCode>=200&&l.statusCode<400?c("ok"):c("http_error")});i.on("error",()=>c("error")),i.setTimeout(C,()=>{i.destroy(),c("timeout")}),i.end()}catch{c("error")}})}function x(){if(p!==void 0)return p;const g=process.env.SF_FUNCSPAN_RUNTIME_ENABLED;if(g==="true"||g==="1")return p=!0,!0;if(g==="false"||g==="0")return p=!1,!1;try{const{isRuntimeModeConfigured:I}=require("../funcSpanConfigLoader");if(I&&I())return p=!0,!0}catch{}return p=!1,!1}function U(){return J!==void 0||(J=!Q()),J}exports.CustomJSONEncoderForFrameInfo=H,exports.https=E,exports.initializeExceptionInterceptor=function(g){d.getConfig().sfDebug&&W("Initializing Exception Interceptor...");try{const n=Q();g?.setSupplementalFields?.({isFromLocalService:n}),(async function(A){if(L)return;L=!0;const o=process.env||{};if(T(o.SF_IS_LOCAL)===void 0)try{await(async function(t){const Z=w("http://169.254.169.254/latest/meta-data/",{},t),Y=w("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},t),m=w("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},t);return(await Promise.allSettled([Z,Y,m])).some(s=>s.status==="fulfilled"&&(s.value==="ok"||s.value==="http_error"))})(150)&&y&&(y=!1,A?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(g).catch(()=>{})}catch{}const I=new P.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEg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ZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHsgc2NyaXB0U291cmNlIH0gPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgIkRlYnVnZ2VyLmdldFNjcmlwdFNvdXJjZSIsCiAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAg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KGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBsb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+IHsKICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlcjoiLCBlcnJvcik7CiAgfQp9KTsKCi8vIEtlZXAgdGhlIHdvcmtlciBhbGl2ZQpzZXRJbnRlcnZhbCgoKSA9PiB7fSwgMTAwMDApOwo="),{workerData:{captureAllExceptions:!0}});let C=null;const c=new WeakMap;I.on("message",n=>{if(typeof n=="string"&&d.getConfig().sfDebug&&W(`[Worker] ${n}`),n.readyToGetParameters&&I.postMessage({sfDebug:d.getConfig().sfDebug,stackDepthLocals:d.getConfig().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:d.getConfig().nodeModulesToCollectLocalVariablesOn}),n.type==="exception"){const{frames:A}=n,o=C;if(!o)return;const t=c.get(o),Z=(function(m){return m?m.split(`
7
+ `).slice(1).map(s=>{const V=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(s)||/at (.+):(\d+):(\d+)/.exec(s);if(V){const[,u,r,G,b]=V;return new N({function:u||"<anonymous>",locals:{},file:r||"<unknown>",line:parseInt(G,10)||0,code:"<not captured>",column:parseInt(b)||0})}return new N({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(o.stack),Y=(function(m,s){const V=[];let u=-1,r=-1;for(let G=0;G<m.length;G++){const b=cI(m[G].file);if(r=G,b!=="<unknown>"){for(let a=0;a<s.length;a++){const v=s[a];if(j(v,b)||typeof v.file=="string"&&v.file.includes(b)){u=a,X=0,d.getConfig().sfDebug&&W(`✅ Matched Frame Found: ${b} @ Debugger Frame ${a}`);break}}if(u!==-1)break}}if(u===-1)return X===10?(X=0,m):(++X,d.getConfig().sfDebug&&W(`"❌ No matching frame found. Checking once again, Attempt N ${X}"`),[]);d.getConfig().sfDebug&&W(`🔄 Merging from matched index ${u} onward...`);for(let G=0;G<s.length;G++){const b=m[r+G],a=s[u+G];V.push(new N({function:a?.function||b?.function||"<anonymous>",locals:a?.locals||b?.locals||{},file:b?.file||a?.file||"<unknown>",line:a?.line||b?.line||0,code:a?.code||b?.code||"<not captured>"}))}return V})(Z,A||[]);if(Y.length!==0){C=null;const m=d.getConfig().stackDepthCodeTraceDepth,s=m===-1?Y:Y.slice(0,m+1),V=Math.min(s.length,Z.length);for(let b=0;b<V;b++)(async()=>{const a=CI(s[b].file,Z[b].line,Z[b].column);a&&(a.content!=null&&(s[b].code=a.content),a.file!=null&&(s[b].file=a.file))})();g.setOperationName("CollectExceptions");const u=o.message?`${o.name}: ${o.message}`:o.name;d.getConfig().sfDebug&&W("error message is : ",u);const r=d.ContextManager.getInstance(),G=c.get(o);G?(r.setTraceIdFor(G,G),r.runWithSession(G,()=>{r.setTraceId(G),g.doSend(u,s)})):g.doSend(u,s),t?d.ContextManager.getInstance().runWithSession(t,()=>{g.doSend(u,s)}):g.doSend(u,s)}}}),I.on("error",n=>{f("[Worker Error]",n)}),I.on("exit",n=>{f(`[Worker] Exited with code ${n}`)}),I.unref();const e=Error,i=new Set;function l(...n){const A=Reflect.construct(e,n);Reflect.setPrototypeOf(A,l.prototype);try{const t=d.ContextManager.getInstance().getTraceId();c.set(A,t)}catch{}e.captureStackTrace&&e.captureStackTrace(A,l);const o=`${A.message}:${A.stack?.split(`
8
+ `)[1]?.trim()}`;if(!i.has(o)){i.add(o),C=A;const t=d.ContextManager.getInstance().getTraceId();c.set(A,t),I.postMessage({type:"processException",error:A.message})}return A}l.prototype=Object.create(e.prototype,{constructor:{value:l,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(l,e),globalThis.Error=l},exports.initializeLogInterceptor=function(g){function I(C,c){const e=d.getGlobalConfigUnsafe();if(e?.logIgnoreRegex&&e.logIgnoreRegex.test(c))return;const[i,l]=gI(2);g.setOperationName("CollectLogs"),g.doSend([c,C,i,l])}console.log=(...C)=>{if(B)K(...C);else{B=!0;try{I("INFO",C.join(" ")),K(...C)}finally{B=!1}}},console.error=(...C)=>{if(B)S(...C);else{B=!0;try{I("ERROR",C.join(" ")),S(...C)}finally{B=!1}}},console.warn=(...C)=>{if(B)F(...C);else{B=!0;try{I("WARN",C.join(" ")),F(...C)}finally{B=!1}}},console.info=(...C)=>{if(B)R(...C);else{B=!0;try{I("INFO",C.join(" ")),R(...C)}finally{B=!1}}},d.getConfig().logLevel==="DEBUG"&&(console.debug=(...C)=>{if(B)z(...C);else{B=!0;try{I("DEBUG",C.join(" ")),z(...C)}finally{B=!1}}})},exports.internalError=f,exports.internalLog=W,exports.isProductionEnvironment=U,exports.isRuntimeModeEnabled=x,exports.shouldEnableRuntimeHooks=function(){return!!x()&&(!U()||(console.warn("[FuncSpan Runtime] DISABLED in production environment"),!1))};
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./contextManager-BkETRITg.cjs"),p=require("./workerPoolSpanCapture-D85i6nhQ.cjs"),h=require("./runtimeConfig-DIsq-KCn.cjs"),se=require("node:module"),x=require("fs"),ae=require("./source-map-rHHEdpre.cjs"),ce=require("path"),de=require("glob"),N=require("worker_threads"),U=require("./funcSpanTransformer-B9WWl-g1.cjs");function ie(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const o=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const O=ie(x),v=ie(ce);class F 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-CxQqBCEA.cjs"),p=require("./workerPoolSpanCapture-COwiNikM.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=`
2
2
  ${this.queryType} ${this.operationName}(
3
3
  $apiKey: String!,
4
4
  $timestampMs: String!,
@@ -9,6 +9,10 @@
9
9
  $library: String!,
10
10
  $version: String!,
11
11
  $gitSha: String!,
12
+ $gitOrg: String,
13
+ $gitRepo: String,
14
+ $gitProvider: String,
15
+ $serviceDisplayName: String,
12
16
  ) {
13
17
  ${this.queryName}(
14
18
  apiKey: $apiKey,
@@ -20,13 +24,17 @@
20
24
  library: $library,
21
25
  version: $version,
22
26
  gitSha: $gitSha,
27
+ gitOrg: $gitOrg,
28
+ gitRepo: $gitRepo,
29
+ gitProvider: $gitProvider,
30
+ serviceDisplayName: $serviceDisplayName,
23
31
  )
24
32
  }
25
- `,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||""});p.nonBlockingPost(this.endpoint,this.operationName,e,t)}}function le(n){try{return JSON.stringify(n),!0}catch{return!1}}class ue extends p.BaseTransmitter{serviceIdentifier=new F;constructor(){super(),this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e,t,o,r){this.sendAppIdentifier(),this.send(e,t,o,r)}async send(e,t,o,r){if(!t&&!r)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let i=[];if(!r){const s=(function(d){const a={},u=[];if(d)for(const[f,m]of Object.entries(d))le(m)?a[f]=m:u.push(f);return{traitsJson:JSON.stringify(a),excludedFields:u}})(t);r=s.traitsJson,i=s.excludedFields}const l=this.getVariables({userId:e,traitsJson:r,excludedFields:i,override:o,library:c.getConfig().packageLibraryType,version:c.getConfig().version});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),l)}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});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`
26
34
  mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
27
35
  ${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
28
36
  }
29
- `}}class B{constructor(e){this.apiKey=e,this.metadataTransmitter=new ue}metadataTransmitter;identify(e,t,o,r=!1){t||o?this.addOrUpdateMetadata(e,t,o,r):this.addOrUpdateMetadata(e,{},void 0,r)}addOrUpdateMetadata(e,t={},o,r=!1){if(!t&&!o)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,o),this.metadataTransmitter.doSend(e,t,r,o)}}class G extends p.BaseTransmitter{serviceIdentifier=new F;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],o=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(),o)}catch(t){c.getConfig().sfDebug&&console.error("🚨 Error in send():",t)}}getQuery(){return`
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`
30
38
  ${this.queryType} ${this.operationName}(
31
39
  $apiKey: String!,
32
40
  $serviceUuid: String!,
@@ -50,7 +58,7 @@
50
58
  sourceLine: $sourceLine
51
59
  )
52
60
  }
53
- `}}class pe extends p.BaseTransmitter{serviceIdentifier=new F;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 o=JSON.stringify(h.CustomJSONEncoderForFrameInfo.encode(t)),r=this.normalizedSupplementalForGraphQL(),i=this.getVariables({exceptionMessage:e,traceJson:o,reentrancyGuardPreactive:!1,library:c.getConfig().packageLibraryType,version:c.getConfig().version,...r});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}getQuery(){return`
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`
54
62
  mutation ${this.operationName}(
55
63
  $apiKey: String!,
56
64
  $serviceUuid: String!,
@@ -78,7 +86,7 @@
78
86
  parentSpanId: $parentSpanId
79
87
  )
80
88
  }
81
- `}}const j="getting request source code";var D=(n=>(n.UNKNOWN="unknown",n.ANONYMOUS="anonymous",n.NOT_CAPTURED="not captured",n))(D||{});const L="http:",k="https:",ge=se.createRequire(require("node:url").pathToFileURL(__filename).href);let z=!1;function fe(){const n=c.getConfig().sfDebug;if(z)return void(n&&h.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;z=!0;try{e=ge("node:http"),n&&h.internalLog("[patchNodeHttpInbound] node:http required successfully.")}catch(r){return void h.internalError("Failed to require node:http:",r)}if(!e?.Server?.prototype)return void(n&&h.internalLog("[patchNodeHttpInbound] http.Server.prototype not found."));const t=e.Server.prototype,o=t.emit;o&&!t.__sf_inbound_patched__?(Object.defineProperty(t,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),n&&h.internalLog("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(r,...i){if(r!=="request")return n&&h.internalLog(`[patchNodeHttpInbound] Passing through event: ${r}`),o.call(this,r,...i);const l=i[0],s=i[1],d=(function(g){const S={};if(!g)return S;for(const[I,_]of Object.entries(g))_!=null&&(Array.isArray(_)?S[I.toLowerCase()]=_.join(", "):S[I.toLowerCase()]=String(_));return S})(l?.headers),a=d["x-sf3-rid"],u=d["x-sf3-functionspancaptureoverride"];n&&(h.internalLog("[patchNodeHttpInbound] Intercepted request event."),h.internalLog("[patchNodeHttpInbound] Inbound headers:",d),h.internalLog("[patchNodeHttpInbound] Trace header:",a),h.internalLog("[patchNodeHttpInbound] FuncSpan override header:",u));const f=c.ContextManager.getInstance();f.setTraceId(a);const m=f.getTraceId();n&&h.internalLog("[patchNodeHttpInbound] Context traceId set:",m);const y=()=>f.runWith({inboundHeaders:d,...a?{traceId:a}:{}},()=>{a&&f.setTraceId(a),n&&h.internalLog("[patchNodeHttpInbound] Running request handler in context.");const g=()=>{n&&h.internalLog("[patchNodeHttpInbound] Response finished/closed for traceId:",f.getTraceId())};return s.on("finish",g),s.on("close",g),o.call(this,r,l,s)});if(!u)return y();try{return p.funcspanOverrideStorage.run(u,()=>y())}catch{return y()}}):n&&h.internalLog("[patchNodeHttpInbound] Already patched, skipping.")}class he extends G{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
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=`
82
90
  ${this.queryType} ${this.operationName}(
83
91
  $apiKey: String!,
84
92
  $serviceUuid: String!,
@@ -90,7 +98,7 @@
90
98
  domains: $domains
91
99
  )
92
100
  }
93
- `,o={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};p.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class me extends p.BaseTransmitter{serviceIdentifier=new F;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:o,line:r,entrypoint:i,retryWithoutTraceId:l}=e,s=this.getVariables({name:t,column:o,line:r,entrypoint:i,retryWithoutTraceId:l});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}getQuery(){return`
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`
94
102
  mutation ${this.operationName}(
95
103
  $apiKey: String!,
96
104
  $sessionId: String!,
@@ -114,15 +122,15 @@
114
122
  ${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
115
123
  )
116
124
  }
117
- `}}class Se extends p.BaseTransmitter{serviceIdentifier=new F;constructor(){super(),this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(e){this.sendAppIdentifier(),this.send(e)}getQuery(){return`
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`
118
126
  mutation ${this.operationName}(
119
127
  $data: NetworkRequestInput!
120
128
  ) {
121
129
  ${this.queryName}(
122
130
  data: $data)
123
131
  }
124
- `}async send(e){const t={data:{...e}};await p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}}const R=[400,403];class ye{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 o;if(e instanceof Headers)o=e.get(t)??void 0;else{const i=t.toLowerCase();for(const[l,s]of Object.entries(e))if(l.toLowerCase()===i){o=s;break}}if(!o)return{};const r=o.split("/").filter(Boolean);return r.length<3?{}:{sessionId:r[0],pageVisitId:r[1],requestId:r[r.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,o,r,i]=t;return{filePath:o,line:parseInt(r,10),column:parseInt(i,10)}}async getOriginalPosition(e,t,o){let r={source:e,line:t,column:o,name:null};const i=e+".map";try{const l=JSON.parse(x.readFileSync(i,"utf-8"));let s=(await new ae.sourceMapExports.SourceMapConsumer(l)).originalPositionFor({line:t,column:o});s.source&&(r=s)}catch(l){c.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${i}:`,l)}return{originalPos:r}}captureFirstUserLines(e,t=10,o=!1){const r=c.getConfig().sfDebug?10:t,i=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(i,r);const l=new Error(j);j in Error&&Error.captureStackTrace(l,this.captureFirstUserLines);const s=l.stack||"";Error.stackTraceLimit=i;const d=s.split(`
125
- `).slice(1),a=[];for(const u of d)if(!(u.includes("node:internal")||u.includes("internal/modules")||u.includes("internal/process")||u.includes("node_modules")||u.includes(".next/server/chunks")||u.includes("RequestInterceptor")||u.includes("contextManager")||u.includes("setupConfig"))&&(a.push(u.trim()),a.length>=t))break;for(const u of a){const f=this.parseStackFrame(u);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 y={line:m.line?.toString()||D.UNKNOWN,column:m.column?.toString()||D.NOT_CAPTURED,name:m.name||D.NOT_CAPTURED,entrypoint:m.source,retryWithoutTraceId:o};e.doSend(y)}})():c.getConfig().sfDebug&&console.error("Could not parse stack line:",u)}}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 o=new URL(t).hostname,r=this.shouldPropagateHeaders(o);return r?this.addTracingHeader(e,t):c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${o}`),r}addTracingHeader(e,t){const o=p.getFuncspanOverride();if(o){const s=p.parseHeaderOverride(o);if(s&&s.sample_rate===0)return void(c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const r=this.contextManager.getOrSetSfTraceId(),i=this.contextManager.getOrSetPageVisitUUID(),l=c.v4();e.set(this.HEADER_TRACING,`${r}/${i}/${l}`),c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const o=globalThis.fetch;typeof o=="function"?globalThis.fetch=async(r,i)=>{const l=new Headers(i?.headers);if(l.get(this.HEADER_LOG_GUARD)==="true"||l.get(this.HEADER_PRINT_GUARD)==="true"||l.get(this.HEADER_EXCEPTION_GUARD)==="true")return o(r,i);this.captureFirstUserLines(e);const s=Date.now();let d;typeof r=="string"||r instanceof URL?d=r.toString():r instanceof Request?(d=r.url,r.headers.forEach((g,S)=>{l.set(S,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,u=new Headers(l),f=this.addTracingHeaders(l,d),m={...i,headers:l};let y;try{let g=!1;this.addTracingHeaders(u,d),y=await o(d,m),f&&R.includes(y.status)?(y=await o(d,{...i,headers:u}),g=!0,this.captureFirstUserLines(e,10,g)):this.contextManager.addSupportedDomains(a);const S=Date.now();c.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${d}, Status: ${y.status}, Duration: ${S-s}ms`);const{sessionId:I,pageVisitId:_,requestId:b}=this.extractIdsFromTraceHeader(l);return t.doSend({apiKey:c.getConfig().apiKey,requestId:b,pageVisitId:_,recordingSessionId:I,serviceUuid:c.getConfig().serviceUUID,timestampStart:s.toString(),timestampEnd:S.toString(),responseCode:y.status,success:!0,error:null,url:d,method:m.method||"GET",retryWithoutTraceId:g,parentSpanId:c.getCurrentFunctionSpanId()}),y}catch(g){const S=Date.now();c.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${d}, Error: ${g}, Duration: ${S-s}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 o=h.https.request.bind(h.https),r=h.https.request.bind(h.https);h.https.request=function(i,l){let s;try{if(typeof i=="string"){const a=new URL(i);s={protocol:a.protocol||L,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||L,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=L));if(s.headers){const a=`${s.protocol}//${s.hostname}`;this.addTracingHeaders(s.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 o(s,a=>{const u=`${s.protocol}//${s.hostname}`;if(s.headers&&this.shouldPropagateHeaders(new URL(u).hostname)&&R.includes(a.statusCode||0)){s.hostname;const g={...s,headers:{...s.headers}};delete g.headers[this.HEADER_TRACING],o(g,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:y}=this.extractIdsFromTraceHeader(s.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:y,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:u,method:s.method||"GET",retryWithoutTraceId:d,parentSpanId:c.getCurrentFunctionSpanId()}),l?.(a)})},h.https.request=function(i,l){let s;try{if(typeof i=="string"){const a=new URL(i);s={protocol:a.protocol||k,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||k,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=k));if(s.headers){const a=`${s.protocol}//${s.hostname}`;this.addTracingHeaders(s.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 r(s,a=>{const u=`${s.protocol}//${s.hostname}`;if(s.headers&&this.shouldPropagateHeaders(new URL(u).hostname)&&R.includes(a.statusCode||0)){const g={...s,headers:{...s.headers}};delete g.headers[this.HEADER_TRACING],r(g,l),d=!0,this.captureFirstUserLines(e,10,d)}const{sessionId:f,pageVisitId:m,requestId:y}=this.extractIdsFromTraceHeader(s.headers);t.doSend({apiKey:c.getConfig().apiKey,requestId:y,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:u,method:s.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 Ie extends G{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const e=`
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=`
126
134
  ${this.queryType} ${this.operationName}(
127
135
  $apiKey: String!,
128
136
  $serviceUuid: String!,
@@ -131,6 +139,14 @@
131
139
  $serviceVersion: String,
132
140
  $serviceAdditionalMetadata: JSON,
133
141
  $gitSha: String!,
142
+ $gitOrg: String,
143
+ $gitRepo: String,
144
+ $gitProvider: String,
145
+ $serviceDisplayName: String,
146
+ $infrastructureType: String,
147
+ $infrastructureDetails: JSON,
148
+ $setupInterceptorsFile: String,
149
+ $setupInterceptorsLine: Int,
134
150
  ) {
135
151
  ${this.queryName}(
136
152
  apiKey: $apiKey,
@@ -140,8 +156,17 @@
140
156
  serviceVersion: $serviceVersion,
141
157
  serviceAdditionalMetadata: $serviceAdditionalMetadata,
142
158
  gitSha: $gitSha,
159
+ gitOrg: $gitOrg,
160
+ gitRepo: $gitRepo,
161
+ gitProvider: $gitProvider,
162
+ serviceDisplayName: $serviceDisplayName,
163
+ infrastructureType: $infrastructureType,
164
+ infrastructureDetails: $infrastructureDetails,
165
+ setupInterceptorsFile: $setupInterceptorsFile,
166
+ setupInterceptorsLine: $setupInterceptorsLine,
143
167
  )
144
168
  }
145
- `,t=this.getVariables({serviceIdentifier:c.getConfig().serviceIdentifier,serviceVersion:c.getConfig().serviceVersion,serviceAdditionalMetadata:c.getConfig().serviceAdditionalMetadata,gitSha:c.getConfig().gitSha||""});p.nonBlockingPost(this.endpoint,this.operationName,e,t)}}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)O.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 o=this.hasSailfishFiles?p.getEnvConfig():p.getDefaultConfig(),r=this._getDirectoryConfig(e),i=v.normalize(e),l=this.fileConfigs.get(i)||{};let s={};if(t){const d=this.functionConfigs.get(i);d&&(s=d.get(t)||{})}return p.mergeConfigs(o,r,l,s)}hasRuntimeMode(){return this.runtimeModeEnabled}async _walkDirectory(e,t){try{const o=O.readdirSync(e,{withFileTypes:!0});for(const r of o){const i=v.join(e,r.name);r.isFile()&&r.name===".sailfish"?t.push(i):r.name==="node_modules"||r.isDirectory()&&r.name.startsWith(".")&&r.name!==".sailfish"||r.isDirectory()&&await this._walkDirectory(i,t)}}catch(o){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,o)}}async _loadConfigFile(e){try{const t=O.readFileSync(e,"utf-8"),o=v.dirname(e);let r=null;try{r=JSON.parse(t)}catch{try{r=require("js-yaml").load(t)}catch(i){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,i))}}if(!r)return;r.runtime_mode===!0&&(this.runtimeModeEnabled=!0,this.debug&&console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${e}`)),r.default&&this.directoryConfigs.set(o,r.default),r.files&&await this._expandFileGlobs(o,r.files,r.default||{}),r.functions&&this._storeFunctionConfigs(o,r.functions,r.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${o}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,o){for(const[r,i]of Object.entries(t))try{const l=v.join(e,r),s=await de.glob(l,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${s.length} files`);for(const d of s){const a=v.normalize(d),u=p.mergeConfigs(o,i);this.fileConfigs.set(a,u),this.debug&&s.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${d}`)}}catch(l){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`,l)}}_storeFunctionConfigs(e,t,o){for(const[r,i]of Object.entries(t)){const l=r.split("::");if(l.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);continue}const[s,d]=l,a=v.normalize(v.join(e,s));this.functionConfigs.has(a)||this.functionConfigs.set(a,new Map);const u=this.functionConfigs.get(a),f=p.mergeConfigs(o,i);u.set(d,f),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${a}::${d}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=v.dirname(v.normalize(e));const o=[];for(;t&&t!==v.dirname(t);){const r=this.directoryConfigs.get(t);r&&o.unshift(r),t=v.dirname(t)}return o.reduce((r,i)=>p.mergeConfigs(r,i),{})}}let C=null;async function J(n,e){C=new _e(n,e),await C.loadAllConfigs()}function V(n,e){return C?C.getConfig(n,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),p.getEnvConfig())}function Q(){return C!==null}const ve=["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"],be=["pbkdf2","randomBytes","scrypt","generateKeyPair"],$e=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Y=!1;function Ce(n){if(typeof n!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&n.includes(e))return!0;const t=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!t||!n.includes(t))}let Z=!1;function ee(n){if(typeof n!="string")return!1;if(n==="localhost"||n==="127.0.0.1"||n==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&n===new URL(e).hostname)return!0}catch{}return!1}function Fe(){if(!Z)try{let n;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{n=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(n.__sf_worker_pool_patched__)return;Object.defineProperty(n,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of X)if(typeof n[e]=="function"){const t=n[e];n[e]=function(...o){return ee(o[0])?t.apply(this,o):typeof o[o.length-1]=="function"?p.captureWorkerPoolOperation("dns",e,t,o,this):t.apply(this,o)},Object.defineProperty(n[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 o=e.promises[t];e.promises[t]=function(...r){return ee(r[0])?o.apply(this,r):p.captureWorkerPoolPromiseOperation("dns",t,o,r,this)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(n),Z=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let te=!1,ne=!1,H=!1;function re(){if(H)return;const n=process.env.SF_DEBUG==="true";n&&console.log("[WorkerPool] Initializing worker pool patching..."),p.isModuleTrackingEnabled("fs")&&(n&&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 ve)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return Ce(r[0])?o.apply(this,r):typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("fs",t,o,r,this):o.apply(this,r)},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)}})()),p.isModuleTrackingEnabled("dns")&&(n&&console.log("[WorkerPool] Patching dns module..."),Fe()),p.isModuleTrackingEnabled("crypto")&&(n&&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 be)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("crypto",t,o,r,this):o.apply(this,r)},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)}})()),p.isModuleTrackingEnabled("zlib")&&(n&&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 $e)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?p.captureWorkerPoolOperation("zlib",t,o,r,this):o.apply(this,r)},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)}})()),H=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function oe(){return H}let A=!1,M=!1,q=null;function E(n){const e=c.getGlobalConfigUnsafe(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:n.functionName,file:n.filePath,duration:`${n.duration}ms`,async:n.async,error:n.error,spanId:n.spanId});const o={functionName:n.functionName,filePath:n.filePath,metadata:n.metadata,args:n.args,result:n.result,error:n.error,duration:n.duration,durationNs:n.durationNs,async:n.async,spanId:n.spanId,parentSpanId:n.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
146
- 📊 Function Span:`,{function:`${n.functionName} (${n.filePath}:${n.metadata.line}:${n.metadata.column})`,duration:`${n.duration.toFixed(2)}ms`,arguments:n.args,result:n.error?`Error: ${n.error}`:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId||"none"});const r=process.env.SF_FUNCSPAN_JSONL_FILE;if(r)try{const i=r==="true"||r==="1"?"funcspans.jsonl":r,l=Date.now(),s=process.hrtime.bigint(),d=BigInt(n.startTimeNs),a=Number(s-d)/1e6,u=new Date(l-a).toISOString(),f=JSON.stringify({timestamp:u,functionName:n.functionName,filePath:n.filePath,line:n.metadata.line,column:n.metadata.column,duration:n.duration,durationNs:n.durationNs,startTimeNs:n.startTimeNs,arguments:n.args,returnValue:n.error?{error:String(n.error)}:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId,async:n.async,pid:n.pid,threadId:n.threadId})+`
147
- `;x.appendFileSync(i,f,"utf-8")}catch(i){console.error("[FuncSpan] Error writing to JSONL file:",i)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",o),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(q||(q=new p.FunctionSpanTransmitter),q).send([o]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(i){t&&console.error("[FuncSpan] Error sending function span:",i)}}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=U.setSkipTypeScriptPlugin,exports.transformFunctionSpans=U.transformFunctionSpans,exports.transformFunctionSpansSync=U.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(n,e={},t,o=!1){const r=c.getConfig();new B(r.apiKey).addOrUpdateMetadata(n,e,t,o)},exports.captureFunctionSpan=function(n,e,t,o){const r=function(...i){const l=c.getGlobalConfigUnsafe(),s=l?.sfDebug||!1;s&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const d=(function(S,I){const _=p.getFuncspanOverride();if(_){const b=p.parseHeaderOverride(_);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${S}::${I}`),b}try{return V(S,I)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(s&&console.log(`[FuncSpan] Config for ${t}::${e}:`,d),d.enable_sampling&&d.sample_rate<1&&Math.random()>d.sample_rate)return s&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),n.apply(this,i);if(d.sample_rate===0)return s&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),n.apply(this,i);s&&console.log(`[FuncSpan] Capturing function span for ${e}`);const a=c.ContextManager.getInstance(),u=a.getCurrentFunctionSpanId(),f=c.v4();a.setCurrentFunctionSpanId(f);const m=process.hrtime.bigint(),y=Date.now();let g=null;d.capture_arguments&&(g={},o.paramNames.forEach((S,I)=>{I<i.length&&(g[S]=i[I])}),g&&d.arg_limit_mb>0&&(g=p.truncateToLimit(g,d.arg_limit_mb)));try{const S=n.apply(this,i);if(S&&typeof S.then=="function")return u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S.then($=>{const P=process.hrtime.bigint(),T=Date.now(),w=Number(P-m);let K=null;return d.capture_return_value&&d.return_limit_mb>0&&(K=p.truncateToLimit($,d.return_limit_mb)),E({functionName:e,filePath:t,metadata:o,args:g,result:K,error:null,duration:T-y,durationNs:w,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:N.threadId}),$},$=>{const P=process.hrtime.bigint(),T=Date.now(),w=Number(P-m);throw E({functionName:e,filePath:t,metadata:o,args:g,result:null,error:$?.message||String($),duration:T-y,durationNs:w,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:N.threadId}),$});const I=process.hrtime.bigint(),_=Date.now(),b=Number(I-m);let W=null;return d.capture_return_value&&d.return_limit_mb>0&&(W=p.truncateToLimit(S,d.return_limit_mb)),E({functionName:e,filePath:t,metadata:o,args:g,result:W,error:null,duration:_-y,durationNs:b,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:N.threadId}),u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S}catch(S){const I=process.hrtime.bigint(),_=Date.now(),b=Number(I-m);throw E({functionName:e,filePath:t,metadata:o,args:g,result:null,error:S?.message||String(S),duration:_-y,durationNs:b,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:N.threadId}),u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S}};Object.defineProperty(r,"name",{value:e,writable:!1});for(const i in n)n.hasOwnProperty(i)&&(r[i]=n[i]);return r},exports.getGlobalConfig=V,exports.identify=function(n,e,t,o=!1){const r=c.getConfig();new B(r.apiKey).identify(n,e,t,o)},exports.initializeConfigLoader=J,exports.initializeWorkerPoolPatching=re,exports.isAlreadyInstrumented=function(n){return!!n.includes("captureFunctionSpan(")||!!n.includes("@sailfish-ai/sf-veritas")||!(!n.includes("/* @sailfish-instrumented */")&&!n.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=Q,exports.isSetupInterceptorsInitialized=function(){return A},exports.isWorkerPoolInitialized=oe,exports.setupInterceptors=function(n){if(M)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!A){M=!0;try{if(!n||!n.apiKey){const r=`The required API Key is not provided: ${JSON.stringify(n)}`;console.error(r)}const{config:e}=c.getOrCreateConfig(n);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const r=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(r),new Error(r)}Q()||J(void 0,e.sfDebug).catch(r=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",r)}),process.env.SF_WORKER_POOL_DISABLED==="true"?e.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):oe()||(re(),e.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const t=new G;t.setServiceUUID(e.serviceUUID),h.initializeLogInterceptor(t),(function(r=[]){const i=new ye(r);new he().doSend(i.getExcludedDomains());const l=new me,s=new Se;i.patchFetch(l,s),i.patchHttp(l,s)})(e.domainsToNotPropagateHeadersTo);const o=new pe;o.setServiceUUID(e.serviceUUID),h.initializeExceptionInterceptor(o),fe(),new Ie().send(),A=!0,e.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{M=!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});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 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 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}}};