@sailfish-ai/sf-veritas 0.2.11 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contextManager-BkETRITg.cjs +1 -0
- package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
- package/dist/plugins/funcspanEsbuildPlugin.mjs +1 -1
- package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
- package/dist/plugins/funcspanRollupPlugin.mjs +1 -1
- package/dist/plugins/funcspanTscPlugin.cjs +1 -1
- package/dist/plugins/funcspanTscPlugin.mjs +1 -1
- package/dist/plugins/funcspanVitePlugin.cjs +1 -1
- package/dist/plugins/funcspanVitePlugin.mjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.mjs +1 -1
- package/dist/{runtimeConfig-emBNO3lJ.js → runtimeConfig-CgLfwL3X.js} +2 -2
- package/dist/{runtimeConfig-CpQ27dZD.cjs → runtimeConfig-DIsq-KCn.cjs} +6 -6
- package/dist/sf-veritas.cjs +11 -11
- package/dist/sf-veritas.mjs +28 -29
- package/dist/worker-pool-capture.cjs +1 -1
- package/dist/worker-pool-capture.mjs +1 -1
- package/dist/{workerPoolSpanCapture-B5KN-q4b.js → workerPoolSpanCapture-BYaf3NOr.js} +138 -151
- package/dist/workerPoolSpanCapture-D85i6nhQ.cjs +83 -0
- package/package.json +6 -2
- package/dist/contextManager-CGINtRN5.cjs +0 -1
- package/dist/workerPoolSpanCapture-Dg_WGjmO.cjs +0 -86
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const v=require("async_hooks"),o=[];for(let s=0;s<256;++s)o.push((s+256).toString(16).slice(1));let h;const L=new Uint8Array(16),S={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function p(s,e,t){if(S.randomUUID&&!s)return S.randomUUID();const n=(s=s||{}).random??s.rng?.()??(function(){if(!h){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");h=crypto.getRandomValues.bind(crypto)}return h(L)})();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,(function(r,i=0){return(o[r[i+0]]+o[r[i+1]]+o[r[i+2]]+o[r[i+3]]+"-"+o[r[i+4]]+o[r[i+5]]+"-"+o[r[i+6]]+o[r[i+7]]+"-"+o[r[i+8]]+o[r[i+9]]+"-"+o[r[i+10]]+o[r[i+11]]+o[r[i+12]]+o[r[i+13]]+o[r[i+14]]+o[r[i+15]]).toLowerCase()})(n)}class _{apiKey;apiGraphqlEndpoint;sfDebug;serviceIdentifier;serviceVersion;serviceUUID;serviceAdditionalMetadata;profilingModeEnabled;profilingMaxDepth;profilingMaxVariableSizeKb;domainsToNotPropagateHeadersTo;nodeModulesToCollectLocalVariablesOn;printConfigurationStatuses;logLevel;stackDepthLocals;stackDepthCodeTraceDepth;packageLibraryType;version;gitSha;_serviceIdentificationReceived=!1;constructor(e){this.apiKey=e.apiKey,this.apiGraphqlEndpoint=e?.apiGraphqlEndpoint||process.env.SAILFISH_GRAPHQL_ENDPOINT||"https://api-service.sailfishqa.com/graphql/",this.sfDebug=e?.debug===!0||process.env.SF_DEBUG==="true",this.serviceIdentifier=e?.serviceIdentifier||process.env.SERVICE_IDENTIFIER,this.serviceUUID=p(),this.serviceVersion=e?.serviceVersion||process.env.SERVICE_VERSION,this.gitSha=e?.gitSha||process.env.GIT_SHA||process.env.VERCEL_GIT_COMMIT_SHA,this.serviceAdditionalMetadata=e?.serviceAdditionalMetadata||{},this.profilingModeEnabled=e?.profilingModeEnabled??!1,this.profilingMaxDepth=e?.profilingMaxDepth??5,this.profilingMaxVariableSizeKb=e?.profilingMaxVariableSizeKb??25,this.domainsToNotPropagateHeadersTo=e?.domainsToNotPropagateHeadersTo||[],this.nodeModulesToCollectLocalVariablesOn=e?.nodeModulesToCollectLocalVariablesOn||["_all_"],this.printConfigurationStatuses=process.env.PRINT_CONFIGURATION_STATUSES||"true",this.logLevel=process.env.LOG_LEVEL||"INFO",this.stackDepthLocals=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS,10):5,isNaN(this.stackDepthLocals)&&(this.stackDepthLocals=-1),this.stackDepthCodeTraceDepth=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH,10):-1,isNaN(this.stackDepthCodeTraceDepth)&&(this.stackDepthCodeTraceDepth=-1),this.packageLibraryType="JS/TS BACKEND",this.version=this.getPackageVersion()}getPackageVersion(){return"0.1.15"}get serviceIdentificationReceived(){return this._serviceIdentificationReceived}setServiceIdentificationReceived(e){this._serviceIdentificationReceived=e}}const T=Symbol.for("sailfish.sf_config");function I(){return globalThis[T]}function l(){const s=I();if(!s)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return s}const f=Symbol.for("sf.ctx.storeAls"),a=globalThis,C=a[f]??(a[f]=new v.AsyncLocalStorage),x=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],D=Symbol.for("sf.ctx.als"),u=a[D]??(a[D]=new v.AsyncLocalStorage),E=Symbol.for("sf.ctx.sessionRegistry"),d=a[E]??(a[E]=new Map),g={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(x),supportedDomains:new Set};class c{static GLOBAL_MANAGER_SYMBOL=Symbol.for("sf.ctx.manager");constructor(){}current(){return C.getStore()}ensureStore(){const e=this.current();if(e)return e;const t=new Map;return C.enterWith(t),t}runWith(e,t){const n=this.current()??new Map,r=new Map(n);for(const[i,A]of Object.entries(e))r.set(i,A);return C.run(r,t)}static getInstance(){return a[c.GLOBAL_MANAGER_SYMBOL]||(a[c.GLOBAL_MANAGER_SYMBOL]=new c),a[c.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return u.getStore()||g}setCurrentContext(e){const t=u.getStore()||g;u.enterWith({...t,...e})}ensureSession(e){let t=d.get(e);return t||(t={...g},d.set(e,t)),t}getContextFor(e){return d.get(e)??g}updateContextFor(e,t){const n=this.ensureSession(e);d.set(e,{...n,...t})}runWithSession(e,t){const n={...this.ensureSession(e)};return u.run(n,t)}deleteSession(e){d.delete(e)}getTraceId(){return this.getCurrentContext().traceId}getPageVisitUUID(){return this.getCurrentContext().pageVisitUUID}setTraceId(e){this.setCurrentContext({traceId:e})}setPageVisitUUID(e){this.setCurrentContext({pageVisitUUID:e})}getCurrentFunctionSpanId(){return this.getCurrentContext().currentFunctionSpanId}setCurrentFunctionSpanId(e){this.setCurrentContext({currentFunctionSpanId:e})}clearCurrentFunctionSpanId(){this.setCurrentContext({currentFunctionSpanId:void 0})}getOrSetSfTraceId(e,t=!1){let n=this.getTraceId();return n||(n=e||(t?p():`nonsession-applogs-v3/${l().apiKey}/${p()}`),this.setTraceId(n),l().sfDebug&&console.log(" Created new trace ID:",n),n)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=p(),this.setPageVisitUUID(e),l().sfDebug&&console.log(" Created new page visit UUID:",e),e)}getHandledExceptions(){return this.getCurrentContext().handledExceptions}markExceptionHandled(e){const t=this.getHandledExceptions();t.add(e),this.setCurrentContext({handledExceptions:t})}hasHandledException(e){return this.getHandledExceptions().has(e)}resetHandledExceptions(){this.setCurrentContext({handledExceptions:new Set})}getExcludedDomains(){return this.getCurrentContext().excludedDomains}getSupportedDomains(){return this.getCurrentContext().supportedDomains}addSupportedDomains(e){this.getCurrentContext().supportedDomains.add(e.toLowerCase().trim())}setTraceIdFor(e,t){this.updateContextFor(e,{traceId:t})}setPageVisitUUIDFor(e,t){this.updateContextFor(e,{pageVisitUUID:t})}}exports.ContextManager=c,exports.DEFAULT_DOMAINS_TO_EXCLUDE=x,exports.getConfig=l,exports.getCurrentFunctionSpanId=function(){return c.getInstance().getCurrentFunctionSpanId()},exports.getGlobalConfigUnsafe=I,exports.getOrCreateConfig=function(s){const e=I();if(e)return{config:e};const t=new _(s);return(function(n){globalThis[T]=n})(t),t.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",t),{config:t}},exports.runWithContext=function(s){const e={...c.getInstance().getCurrentContext()};u.run(e,()=>{s()})},exports.v4=p;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("fs"),r=require("../funcSpanTransformer-B9WWl-g1.cjs"),c=require("../runtimeConfig-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("fs"),r=require("../funcSpanTransformer-B9WWl-g1.cjs"),c=require("../runtimeConfig-DIsq-KCn.cjs");function l(o={}){try{if(c.shouldEnableRuntimeHooks())return console.warn("[FuncSpan Esbuild Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"),{name:"sailfish-funcspan-esbuild-disabled",setup(){}}}catch{}const{enabled:a=!0,includeNodeModules:i=[],debug:t=!1}=o;return{name:"sailfish-funcspan-esbuild",setup(u){a&&(u.onLoad({filter:/\.(js|ts|jsx|tsx)$/},async e=>{if(e.path.includes("node_modules")&&!i.some(n=>e.path.includes(`node_modules/${n}`))||e.path.includes("@sailfish-ai/sf-veritas")||e.path.includes("jsts-backend/dist"))return null;try{const n=d.readFileSync(e.path,"utf-8"),s=await r.transformFunctionSpans(n,e.path,{projectRoot:process.cwd(),includeNodeModules:i,debug:t});if(s.modified)return{contents:s.code,loader:e.path.endsWith(".ts")||e.path.endsWith(".tsx")?"ts":"js"}}catch(n){t&&console.error(`[FuncSpan Esbuild] Error transforming ${e.path}:`,n)}return null}),t&&console.log("[FuncSpan Esbuild] Plugin initialized"))}}}exports.default=l,exports.funcspanEsbuildPlugin=l;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFileSync as l } from "fs";
|
|
2
2
|
import { t as d } from "../funcSpanTransformer-CWNEWRxq.js";
|
|
3
|
-
import { s as r } from "../runtimeConfig-
|
|
3
|
+
import { s as r } from "../runtimeConfig-CgLfwL3X.js";
|
|
4
4
|
function h(o = {}) {
|
|
5
5
|
try {
|
|
6
6
|
if (r()) return console.warn("[FuncSpan Esbuild Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"), { name: "sailfish-funcspan-esbuild-disabled", setup() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("../funcSpanTransformer-B9WWl-g1.cjs"),a=require("../runtimeConfig-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("../funcSpanTransformer-B9WWl-g1.cjs"),a=require("../runtimeConfig-DIsq-KCn.cjs");function s(o={}){try{if(a.shouldEnableRuntimeHooks())return console.warn("[FuncSpan Rollup Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"),{name:"sailfish-funcspan-rollup-disabled"}}catch{}const{enabled:t=!0,includeNodeModules:l=[],debug:u=!1}=o;return{name:"sailfish-funcspan-rollup",async transform(r,e){if(!t||!e.match(/\.(js|ts|jsx|tsx)$/)||e.includes("node_modules")&&!l.some(n=>e.includes(`node_modules/${n}`))||e.includes("@sailfish-ai/sf-veritas")||e.includes("jsts-backend/dist"))return null;try{const n=await i.transformFunctionSpans(r,e,{projectRoot:process.cwd(),includeNodeModules:l,debug:u});if(n.modified)return{code:n.code,map:n.map||null}}catch(n){u&&console.error(`[FuncSpan Rollup] Error transforming ${e}:`,n)}return null}}}exports.default=s,exports.funcspanRollupPlugin=s;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as i } from "../funcSpanTransformer-CWNEWRxq.js";
|
|
2
|
-
import { s as r } from "../runtimeConfig-
|
|
2
|
+
import { s as r } from "../runtimeConfig-CgLfwL3X.js";
|
|
3
3
|
function c(o = {}) {
|
|
4
4
|
try {
|
|
5
5
|
if (r()) return console.warn("[FuncSpan Rollup Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"), { name: "sailfish-funcspan-rollup-disabled" };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("fs"),_=require("glob"),N=require("path"),m=require("../funcSpanTransformer-B9WWl-g1.cjs"),T=require("../runtimeConfig-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("fs"),_=require("glob"),N=require("path"),m=require("../funcSpanTransformer-B9WWl-g1.cjs"),T=require("../runtimeConfig-DIsq-KCn.cjs");async function S(n={}){try{if(T.shouldEnableRuntimeHooks())return void console.warn("[FuncSpan TSC Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation")}catch{}const{outDir:f="dist",include:F=["**/*.js"],exclude:g=["**/*.test.js","**/*.spec.js","**/__tests__/**"],projectRoot:c=process.cwd(),includeNodeModules:C=[],debug:s=!1}=n,u=N.resolve(c,f);console.log("[FuncSpan TSC] Starting post-build function instrumentation..."),console.log(`[FuncSpan TSC] Output directory: ${u}`),console.log(`[FuncSpan TSC] Project root: ${c}`);const r=[];for(const e of F){const t=_.sync(e,{cwd:u,absolute:!0,ignore:g});r.push(...t)}console.log(`[FuncSpan TSC] Found ${r.length} JavaScript files to process`);let l=0,a=0;for(const e of r)try{const t=i.readFileSync(e,"utf-8"),o=await m.transformFunctionSpans(t,e,{projectRoot:c,includeNodeModules:C,debug:s});if(o.modified){if(i.writeFileSync(e,o.code,"utf-8"),o.map){const p=`${e}.map`;i.writeFileSync(p,JSON.stringify(o.map),"utf-8"),s&&console.log(`[FuncSpan TSC] Generated source map: ${p}`)}l++,a+=o.functionsWrapped,s&&console.log(`[FuncSpan TSC] Modified: ${e} (${o.functionsWrapped} functions)`)}}catch(t){console.error(`[FuncSpan TSC] Error processing ${e}:`,t)}console.log(`[FuncSpan TSC] ✅ Completed: Modified ${l} files, wrapped ${a} functions`)}async function d(){const n={outDir:process.env.SF_FUNCSPAN_OUT_DIR||"dist",debug:process.env.SF_FUNCSPAN_DEBUG==="true",includeNodeModules:process.env.SF_FUNCSPAN_INCLUDE_NODE_MODULES?process.env.SF_FUNCSPAN_INCLUDE_NODE_MODULES.split(","):[]};await S(n)}require.main===module&&d().catch(n=>{console.error("[FuncSpan TSC] Fatal error:",n),process.exit(1)}),exports.cli=d,exports.processTscFiles=S;
|
|
@@ -2,7 +2,7 @@ import { readFileSync as m, writeFileSync as l } from "fs";
|
|
|
2
2
|
import { sync as g } from "glob";
|
|
3
3
|
import { resolve as C } from "path";
|
|
4
4
|
import { t as _ } from "../funcSpanTransformer-CWNEWRxq.js";
|
|
5
|
-
import { s as N } from "../runtimeConfig-
|
|
5
|
+
import { s as N } from "../runtimeConfig-CgLfwL3X.js";
|
|
6
6
|
async function D(n = {}) {
|
|
7
7
|
try {
|
|
8
8
|
if (N()) return void console.warn("[FuncSpan TSC Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../funcSpanTransformer-B9WWl-g1.cjs"),l=require("../runtimeConfig-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../funcSpanTransformer-B9WWl-g1.cjs"),l=require("../runtimeConfig-DIsq-KCn.cjs");exports.funcspanVitePlugin=function(s={}){try{if(l.shouldEnableRuntimeHooks())return console.warn("[FuncSpan Vite Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"),{name:"sailfish-funcspan-vite-disabled"}}catch{}const{enabled:o=!0,includeNodeModules:t=[],debug:i=!1}=s;return{name:"sailfish-funcspan-vite",enforce:"pre",async transform(u,e){if(!o||!e.match(/\.(js|ts|jsx|tsx)$/)||e.startsWith("\0")||e.includes("node_modules")&&!t.some(n=>e.includes(`node_modules/${n}`))||e.includes("@sailfish-ai/sf-veritas")||e.includes("jsts-backend/dist"))return null;try{const n=await r.transformFunctionSpans(u,e,{projectRoot:process.cwd(),includeNodeModules:t,debug:i});if(n.modified)return{code:n.code,map:null}}catch(n){i&&console.error(`[FuncSpan Vite] Error transforming ${e}:`,n)}return null}}};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as o } from "../funcSpanTransformer-CWNEWRxq.js";
|
|
2
|
-
import { s as l } from "../runtimeConfig-
|
|
2
|
+
import { s as l } from "../runtimeConfig-CgLfwL3X.js";
|
|
3
3
|
function d(u = {}) {
|
|
4
4
|
try {
|
|
5
5
|
if (l()) return console.warn("[FuncSpan Vite Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation"), { name: "sailfish-funcspan-vite-disabled" };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const b=require("../runtimeConfig-DIsq-KCn.cjs"),a=require("path"),P=require("url");function m(r){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const n in r)if(n!=="default"){const t=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(o,n,t.get?t:{enumerable:!0,get:()=>r[n]})}}return o.default=r,Object.freeze(o)}const f=m(a);class u{options;constructor(o={}){this.options={enabled:!0,includeNodeModules:[],debug:!1,enableWorkerPoolTracking:!1,workerPoolTrackDns:!1,workerPoolTrackFs:!1,workerPoolTrackCrypto:!1,workerPoolTrackZlib:!1,...o}}apply(o){try{if(b.shouldEnableRuntimeHooks())return void console.warn("[FuncSpan Webpack Plugin] Runtime mode active - build plugin DISABLED to prevent double-instrumentation")}catch{}const{enabled:n,includeNodeModules:t,debug:c}=this.options;if(!n)return;const l="FuncspanWebpackPlugin";o.hooks.compilation.tap(l,s=>{s.hooks.buildModule.tap(l,i=>{i.resource&&i.resource.match(/\.(js|ts|jsx|tsx)$/)&&(!i.resource.includes("node_modules")||t?.some(e=>i.resource.includes(`node_modules/${e}`)))}),o.webpack.NormalModule.getCompilationHooks(s).loader.tap(l,(i,e)=>{if(!e.resource||!e.resource.match(/\.(js|ts|jsx|tsx)$/)||e.resource.includes("node_modules")&&!t?.some(p=>e.resource.includes(`node_modules/${p}`)))return;const d=typeof __dirname<"u"?__dirname:a.dirname(P.fileURLToPath(require("node:url").pathToFileURL(__filename).href)),k=f.join(d,"funcspanWebpackLoader.cjs");e.loaders.push({loader:k,options:{projectRoot:o.context,includeNodeModules:t,debug:c,enableWorkerPoolTracking:this.options.enableWorkerPoolTracking,workerPoolTrackDns:this.options.workerPoolTrackDns,workerPoolTrackFs:this.options.workerPoolTrackFs,workerPoolTrackCrypto:this.options.workerPoolTrackCrypto,workerPoolTrackZlib:this.options.workerPoolTrackZlib}})})}),c&&console.log("[FuncSpan Webpack] Plugin initialized")}}exports.FuncspanWebpackPlugin=u,exports.default=u;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var k = Object.defineProperty;
|
|
2
2
|
var m = (r, o, s) => o in r ? k(r, o, { enumerable: !0, configurable: !0, writable: !0, value: s }) : r[o] = s;
|
|
3
3
|
var c = (r, o, s) => m(r, typeof o != "symbol" ? o + "" : o, s);
|
|
4
|
-
import { s as b } from "../runtimeConfig-
|
|
4
|
+
import { s as b } from "../runtimeConfig-CgLfwL3X.js";
|
|
5
5
|
import * as P from "path";
|
|
6
6
|
import { dirname as T } from "path";
|
|
7
7
|
import { fileURLToPath as f } from "url";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";
|
|
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(`
|
|
2
2
|
`).slice(o,o+5).join(`
|
|
3
|
-
`)})(g,I),c=
|
|
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||
|
|
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
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 ng(I){return I?.split("/").pop()||"<unknown>"}function T(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"&&T(C,g))return!0;return!1}let X,H,U=!1;function Q(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 O(){if(V!==void 0)return V;const I=process.env||{},g=Q(I.SF_IS_LOCAL);if(g!==void 0)return V=g;const C=(I.SF_ENV||I.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(C))return V=!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 V=!1;const c=(z.hostname?.()||I.HOSTNAME||"").toLowerCase();return V=!(c!=="localhost"&&!c.endsWith(".local")&&!c.includes("local"))}function f(I,g,C){return new Promise(c=>{try{const A=new URL(I),i=(A.protocol,z).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 E(){if(X!==void 0)return X;const I=process.env.SF_FUNCSPAN_RUNTIME_ENABLED;if(I==="true"||I==="1")return X=!0,!0;if(I==="false"||I==="0")return X=!1,!1;try{const{isRuntimeModeConfigured:g}=require("../funcSpanConfigLoader");if(g&&g())return X=!0,!0}catch{}return X=!1,!1}function j(){return H!==void 0||(H=!O()),H}exports.CustomJSONEncoderForFrameInfo=v,exports.https=z,exports.initializeExceptionInterceptor=function(I){d.getConfig().sfDebug&&W("Initializing Exception Interceptor...");try{const l=O();I?.setSupplementalFields?.({isFromLocalService:l}),(async function(e){if(U)return;U=!0;const o=process.env||{};if(Q(o.SF_IS_LOCAL)===void 0)try{await(async function(t){const Z=f("http://169.254.169.254/latest/meta-data/",{},t),h=f("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},t),m=f("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},t);return(await Promise.allSettled([Z,h,m])).some(s=>s.status==="fulfilled"&&(s.value==="ok"||s.value==="http_error"))})(150)&&V&&(V=!1,e?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(I).catch(()=>{})}catch{}const g=new q.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB1bmRlZmluZWQ7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB1bmRlZmluZWQ7CgovKioKICogUHJvY2Vzc2VzIGNhbGwgZnJhbWVzIGZyb20gYW4gZXhjZXB0aW9uIGFuZCBwb3N0cyB0aGVtIHZpYSB0aGUgV29ya2Vy4oCZcyBwYXJlbnRQb3J0LgogKgogKiBAcGFyYW0gc2Vzc2lvbiAtIFRoZSBEZXZUb29scyBzZXNzaW9uIG9yIHNpbWlsYXIgb2JqZWN0IHlvdSB1c2UgdG8gcXVlcnkgZm9yIHNjcmlwdCBzb3VyY2VzLgogKiBAcGFyYW0gY2FsbEZyYW1lcyAtIEFuIGFycmF5IG9mIGNhbGwgZnJhbWUgb2JqZWN0cy4KICogQHBhcmFtIGRlc2NyaXB0aW9uTGluZXMgL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Xb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IiwKICAgICAgICB9OwogICAgICB9CiAgICB9KSwKICApOwogIC8vIFBvc3QgZXhjZXB0aW9uIGRhdGEKICBwYXJlbnRQb3J0Py5wb3N0TWVzc2FnZSh7IHR5cGU6ICJleGNlcHRpb24iLCBmcmFtZXMgfSk7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bWVzc2FnZS5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT247CgogICAgICAgIHJlc29sdmVNZXNzYWdlUHJvbWlzZSgpOwogICAgICB9CiAgICB9IGNhdGNoIChlcnJvcikgewogICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICBjb25zb2xlLmVycm9yKCLinYwgRXJyb3IgaW4gbWVzc2FnZSBoYW5kbGluZzoiLCBlcnJvcik7CiAgICAgIH0KICAgIH0KICB9KTsKCiAgYXdhaXQgbWVzc2FnZVByb21pc2U7CgogIHRyeSB7CiAgICBjb25zdCBzZXNzaW9uID0gbmV3IFNlc3Npb24oKTsKICAgIHNlc3Npb24uY29ubmVjdFRvTWFpblRocmVhZCgpOwoKICAgIHNlc3Npb24ub24oIkRlYnVnZ2VyLnJlc3VtZWQiLCAoKSA9PiB7CiAgICAgIGlzUGF1c2VkID0gZmFsc2U7CiAgICB9KTsKCiAgICBzZXNzaW9uLm9uKCJEZWJ1Z2dlci5wYXVzZWQiLCBhc3luYyAoZXZlbnQpID0+IHsKICAgICAgaXNQYXVzZWQgPSB0cnVlOwogICAgICBoYW5kbGVQYXVzZWQoc2Vzc2lvbiwgZXZlbnQucGFyYW1zKS50aGVuKAogICAgICAgIGFzeW5jICgpID0+IHsKICAgICAgICAgIC8vIEFmdGVyIHRoZSBwYXVzZSB3b3JrIGlzIGNvbXBsZXRlLCByZXN1bWUgZXhlY3V0aW9uIQogICAgICAgICAgaWYgKGlzUGF1c2VkKSB7CiAgICAgICAgICAgIGF3YWl0IHNlc3Npb24ucG9zdCgiRGVidWdnZXIucmVzdW1lIik7CiAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgICBhc3luYyAoXykgPT4gewogICAgICAgICAgaWYgKGlzUGF1c2VkKSB7CiAgICAgICAgICAgIGF3YWl0IHNlc3Npb24ucG9zdCgiRGVidWdnZXIucmVzdW1lIik7CiAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgKTs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cHJvcC5uYW1lLCB2YXJpYWJsZXMpOwogICAgICAgIH0gZWxzZSBpZiAoCiAgICAgICAgICBwcm9wPy52YWx1ZT8ub2JqZWN0SWQgJiYKICAgICAgICAgIHByb3A/LnZhbHVlPy5jbGFzc05hbWUgPT09ICJPYmplY3QiCiAgICAgICAgKSB7CiAgICAgICAgICBjb25zdCBpZCA9IHByb3AudmFsdWUub2JqZWN0SWQ7CiAgICAgICAgICBhd2FpdCB1bnJvbGxPYmplY3Qoc2Vzc2lvbiwgaWQsIHByb3AubmFtZSwgdmFyaWFibGVzKTsKICAgICAgICB9IGVsc2UgaWYgKHByb3A/LnZhbHVlKSB7CiAgICAgICAgICB1bnJvbGxPdGhlcihwcm9wLCB2YXJpYWJsZXMpOwogICAgICAgIH0KICAgICAgfQogICAgICByZXR1cm4gdmFyaWFibGVzOwogICAgfQogIH0gY2F0Y2ggKGVycikgewogICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBsb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+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
|
|
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]=
|
|
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,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFs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ICAgICAgICAgIGNvbnN0IHsgc2NyaXB0U291cmNlIH0gPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgIkRlYnVnZ2VyLmdldFNjcmlwdFNvdXJjZSIsCiAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNh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gd2UgYWxsb3cgY2FwdHVyaW5nIGZyb20KICAgICAgICBjb25zdCBpc0Zyb21BbGxvd2VkTm9kZU1vZHVsZSA9IG5vZGVNb2R1bGVzTGlzdC5zb21lKChtb2R1bGVOYW1lKSA9PgogICAgICAgICAgZmlyc3RGcmFtZUxpbmUuaW5jbHVkZXMoYCR7bW9kdWxlTmFtZX1gKSwKICAgICAgICApOwoKICAgICAgICBpZiAoIWlzRnJvbUFsbG93ZWROb2RlTW9kdWxlKSB7CiAgICAgICAgICAvLyBOb3QgZnJvbSBhbiBhbGxvd2VkIG5vZGUgbW9kdWxlID0+IHJldHVybiBlYXJseQogICAgICAgICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgICAgICAgIGNvbnNvbGUubG9nKAogICAgICAgICAgICAgICJbV29ya2VyXSBFcnJvciBhcHBlYXJzIHRvIGJlIHRyaWdnZXJlZCBmcm9tIG5vbi1hcHBsaWNhdGlvbiBzb3VyY2VzOyBpZ25vcmluZy4iLAogICAgICAgICAgICApOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KICAgICAgICAvLyBPdGhlcndpc2UsIGl0J3MgZnJvbSBhbiBhbGxvd2VkIG5vZGUgbW9kdWxlLCBzbyBjb250aW51ZQogICAgICB9IGVsc2UgewogICAgICAgIC8vIElmIHRoZSBsaXN0IGlzIGVtcHR5LCBwcmVzZXJ2ZSBleGlzdGluZyBiZWhhdmlvciBhbmQgaWdub3JlIG5vbi1hcHBsaWNhdGlvbiBlcnJvcnMKICAgICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICAgIGNvbnNvbGUubG9nKAogICAgICAgICAgICAiW1dvcmtlcl0gRXJyb3IgYXBwZWFycyB0byBiZSB0cmlnZ2VyZWQgZnJvbSBub24tYXBwbGljYXRpb24gc291cmNlczsgaWdub3JpbmcuIiwKICAgICAgICAgICk7CiAgICAgICAgfQogICAgICAgIHJldHVybjsKICAgICAgfQogICAgfQo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sb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+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))};
|
package/dist/sf-veritas.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";
|
|
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=`
|
|
2
2
|
${this.queryType} ${this.operationName}(
|
|
3
3
|
$apiKey: String!,
|
|
4
4
|
$timestampMs: String!,
|
|
@@ -22,11 +22,11 @@
|
|
|
22
22
|
gitSha: $gitSha,
|
|
23
23
|
)
|
|
24
24
|
}
|
|
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
|
|
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`
|
|
26
26
|
mutation ${this.operationName}($apiKey: String!, $serviceUuid: String!, $sessionId: String!, $userId: String!, $traitsJson: String!, $excludedFields: [String!]!, $library: String!, $timestampMs: String!, $version: String!, $override: Boolean!) {
|
|
27
27
|
${this.queryName}(apiKey: $apiKey, serviceUuid: $serviceUuid, sessionId: $sessionId, userId: $userId, traitsJson: $traitsJson, excludedFields: $excludedFields, library: $library, timestampMs: $timestampMs, version: $version, override: $override)
|
|
28
28
|
}
|
|
29
|
-
`}}class
|
|
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`
|
|
30
30
|
${this.queryType} ${this.operationName}(
|
|
31
31
|
$apiKey: String!,
|
|
32
32
|
$serviceUuid: String!,
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
sourceLine: $sourceLine
|
|
51
51
|
)
|
|
52
52
|
}
|
|
53
|
-
`}}class
|
|
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`
|
|
54
54
|
mutation ${this.operationName}(
|
|
55
55
|
$apiKey: String!,
|
|
56
56
|
$serviceUuid: String!,
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
parentSpanId: $parentSpanId
|
|
79
79
|
)
|
|
80
80
|
}
|
|
81
|
-
`}}const
|
|
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=`
|
|
82
82
|
${this.queryType} ${this.operationName}(
|
|
83
83
|
$apiKey: String!,
|
|
84
84
|
$serviceUuid: String!,
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
domains: $domains
|
|
91
91
|
)
|
|
92
92
|
}
|
|
93
|
-
`,o={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};p.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class
|
|
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`
|
|
94
94
|
mutation ${this.operationName}(
|
|
95
95
|
$apiKey: String!,
|
|
96
96
|
$sessionId: String!,
|
|
@@ -114,15 +114,15 @@
|
|
|
114
114
|
${this.operationName==="CollectNetworkHops"?", retryWithoutTraceId: $retryWithoutTraceId":""}
|
|
115
115
|
)
|
|
116
116
|
}
|
|
117
|
-
`}}class
|
|
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`
|
|
118
118
|
mutation ${this.operationName}(
|
|
119
119
|
$data: NetworkRequestInput!
|
|
120
120
|
) {
|
|
121
121
|
${this.queryName}(
|
|
122
122
|
data: $data)
|
|
123
123
|
}
|
|
124
|
-
`}async send(
|
|
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()||
|
|
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=`
|
|
126
126
|
${this.queryType} ${this.operationName}(
|
|
127
127
|
$apiKey: String!,
|
|
128
128
|
$serviceUuid: String!,
|
|
@@ -142,6 +142,6 @@
|
|
|
142
142
|
gitSha: $gitSha,
|
|
143
143
|
)
|
|
144
144
|
}
|
|
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 Ce{constructor(e=[process.cwd()],t=!1){I(this,"rootPaths");I(this,"fileConfigs",new Map);I(this,"functionConfigs",new Map);I(this,"directoryConfigs",new Map);I(this,"hasSailfishFiles",!1);I(this,"runtimeModeEnabled",!1);I(this,"debug");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)k.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=$.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=k.readdirSync(e,{withFileTypes:!0});for(const r of o){const i=$.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=k.readFileSync(e,"utf-8"),o=$.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=$.join(e,r),s=await ge.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=$.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=$.normalize($.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=$.dirname($.normalize(e));const o=[];for(;t&&t!==$.dirname(t);){const r=this.directoryConfigs.get(t);r&&o.unshift(r),t=$.dirname(t)}return o.reduce((r,i)=>p.mergeConfigs(r,i),{})}}let F=null;async function Q(n,e){F=new Ce(n,e),await F.loadAllConfigs()}function X(n,e){return F?F.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 Y(){return F!==null}const Fe=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Z=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ne=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ee=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let ee=!1;function De(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 te=!1;function ne(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 Pe(){if(!te)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 Z)if(typeof n[e]=="function"){const t=n[e];n[e]=function(...o){return ne(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 Z)if(typeof e.promises[t]=="function"){const o=e.promises[t];e.promises[t]=function(...r){return ne(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),te=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let re=!1,oe=!1,G=!1;function ie(){if(G)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(!ee)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Fe)if(typeof e[t]=="function"){const o=e[t];e[t]=function(...r){return De(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})}ee=!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..."),Pe()),p.isModuleTrackingEnabled("crypto")&&(n&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!re)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 Ne)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})}re=!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(!oe)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 Ee)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})}oe=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),G=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function se(){return G}let M=!1,H=!1,x=null;function D(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(`
|
|
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
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
|
-
`;
|
|
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}}};
|