@sailfish-ai/sf-veritas 0.2.7 → 0.2.9

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 (40) hide show
  1. package/dist/contextManager-CEPhVu9T.js +197 -0
  2. package/dist/contextManager-CGINtRN5.cjs +1 -0
  3. package/dist/funcSpanTransformer-B9WWl-g1.cjs +1 -0
  4. package/dist/funcSpanTransformer-CWNEWRxq.js +225 -0
  5. package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
  6. package/dist/plugins/funcspanEsbuildPlugin.mjs +17 -11
  7. package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
  8. package/dist/plugins/funcspanRollupPlugin.mjs +13 -8
  9. package/dist/plugins/funcspanTscPlugin.cjs +1 -1
  10. package/dist/plugins/funcspanTscPlugin.mjs +19 -14
  11. package/dist/plugins/funcspanVitePlugin.cjs +1 -1
  12. package/dist/plugins/funcspanVitePlugin.mjs +15 -10
  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 +22 -17
  17. package/dist/runtime/funcspanRegister.cjs +276 -0
  18. package/dist/runtimeConfig-CpQ27dZD.cjs +8 -0
  19. package/dist/runtimeConfig-emBNO3lJ.js +350 -0
  20. package/dist/sf-veritas.cjs +18 -18
  21. package/dist/sf-veritas.mjs +417 -619
  22. package/dist/source-map-Cr6YkjTd.js +631 -0
  23. package/dist/source-map-rHHEdpre.cjs +1 -0
  24. package/dist/types/dataTransmitter.d.ts +1 -0
  25. package/dist/types/funcSpanConfigLoader.d.ts +10 -0
  26. package/dist/types/index.d.ts +3 -1
  27. package/dist/types/logHandler.d.ts +5 -0
  28. package/dist/types/plugins/funcSpanTransformer.d.ts +13 -0
  29. package/dist/types/runtime/instrumentationDetector.d.ts +33 -0
  30. package/dist/types/runtime/runtimeConfig.d.ts +48 -0
  31. package/dist/types/sourceLocation.d.ts +30 -0
  32. package/dist/worker-pool-capture.cjs +1 -1
  33. package/dist/worker-pool-capture.mjs +1 -1
  34. package/dist/workerPoolSpanCapture-B5KN-q4b.js +528 -0
  35. package/dist/workerPoolSpanCapture-Dg_WGjmO.cjs +86 -0
  36. package/package.json +5 -2
  37. package/dist/funcSpanTransformer-BLhIRZqX.js +0 -765
  38. package/dist/funcSpanTransformer-BpWuHXKT.cjs +0 -1
  39. package/dist/workerPoolSpanCapture-D0-0Z0Jw.js +0 -718
  40. package/dist/workerPoolSpanCapture-DEwlTq0a.cjs +0 -86
@@ -1,86 +0,0 @@
1
- "use strict";var oe=Object.defineProperty;var se=(t,e,n)=>e in t?oe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var c=(t,e,n)=>se(t,typeof e!="symbol"?e+"":e,n);const P=require("async_hooks"),ae=require("fs"),L=require("worker_threads"),l=[];for(let t=0;t<256;++t)l.push((t+256).toString(16).slice(1));let R;const ie=new Uint8Array(16),J={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function v(t,e,n){if(J.randomUUID&&!t)return J.randomUUID();const a=(t=t||{}).random??t.rng?.()??(function(){if(!R){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");R=crypto.getRandomValues.bind(crypto)}return R(ie)})();if(a.length<16)throw new Error("Random bytes length must be >= 16");return a[6]=15&a[6]|64,a[8]=63&a[8]|128,(function(s,i=0){return(l[s[i+0]]+l[s[i+1]]+l[s[i+2]]+l[s[i+3]]+"-"+l[s[i+4]]+l[s[i+5]]+"-"+l[s[i+6]]+l[s[i+7]]+"-"+l[s[i+8]]+l[s[i+9]]+"-"+l[s[i+10]]+l[s[i+11]]+l[s[i+12]]+l[s[i+13]]+l[s[i+14]]+l[s[i+15]]).toLowerCase()})(a)}class ce{constructor(e){c(this,"apiKey");c(this,"apiGraphqlEndpoint");c(this,"sfDebug");c(this,"serviceIdentifier");c(this,"serviceVersion");c(this,"serviceUUID");c(this,"serviceAdditionalMetadata");c(this,"profilingModeEnabled");c(this,"profilingMaxDepth");c(this,"profilingMaxVariableSizeKb");c(this,"domainsToNotPropagateHeadersTo");c(this,"nodeModulesToCollectLocalVariablesOn");c(this,"printConfigurationStatuses");c(this,"logLevel");c(this,"stackDepthLocals");c(this,"stackDepthCodeTraceDepth");c(this,"packageLibraryType");c(this,"version");c(this,"gitSha");c(this,"_serviceIdentificationReceived",!1);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=v(),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 ee=Symbol.for("sailfish.sf_config");function T(){return globalThis[ee]}function f(){const t=T();if(!t)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return t}const j=Symbol.for("sf.ctx.storeAls"),h=globalThis,w=h[j]??(h[j]=new P.AsyncLocalStorage),re=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],q=Symbol.for("sf.ctx.als"),F=h[q]??(h[q]=new P.AsyncLocalStorage),Q=Symbol.for("sf.ctx.sessionRegistry"),E=h[Q]??(h[Q]=new Map),A={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(re),supportedDomains:new Set},I=class I{constructor(){}current(){return w.getStore()}ensureStore(){const e=this.current();if(e)return e;const n=new Map;return w.enterWith(n),n}runWith(e,n){const a=this.current()??new Map,s=new Map(a);for(const[i,r]of Object.entries(e))s.set(i,r);return w.run(s,n)}static getInstance(){return h[I.GLOBAL_MANAGER_SYMBOL]||(h[I.GLOBAL_MANAGER_SYMBOL]=new I),h[I.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return F.getStore()||A}setCurrentContext(e){const n=F.getStore()||A;F.enterWith({...n,...e})}ensureSession(e){let n=E.get(e);return n||(n={...A},E.set(e,n)),n}getContextFor(e){return E.get(e)??A}updateContextFor(e,n){const a=this.ensureSession(e);E.set(e,{...a,...n})}runWithSession(e,n){const a={...this.ensureSession(e)};return F.run(a,n)}deleteSession(e){E.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,n=!1){let a=this.getTraceId();return a||(a=e||(n?v():`nonsession-applogs-v3/${f().apiKey}/${v()}`),this.setTraceId(a),f().sfDebug&&console.log(" Created new trace ID:",a),a)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=v(),this.setPageVisitUUID(e),f().sfDebug&&console.log(" Created new page visit UUID:",e),e)}getHandledExceptions(){return this.getCurrentContext().handledExceptions}markExceptionHandled(e){const n=this.getHandledExceptions();n.add(e),this.setCurrentContext({handledExceptions:n})}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,n){this.updateContextFor(e,{traceId:n})}setPageVisitUUIDFor(e,n){this.updateContextFor(e,{pageVisitUUID:n})}};c(I,"GLOBAL_MANAGER_SYMBOL",Symbol.for("sf.ctx.manager"));let y=I;class te{constructor(){c(this,"apiKey");c(this,"endpoint");c(this,"queryType","mutation");c(this,"operationName","");c(this,"serviceUUID",f().serviceUUID);c(this,"contextManager");this.apiKey=f().apiKey,this.endpoint=f().apiGraphqlEndpoint,this.contextManager=y.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const e=Date.now().toString(),n=this.contextManager.getOrSetSfTraceId(),a=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:n,timestampMs:e,parentSpanId:a}}getVariables(e={}){return{...this.getDefaultVariables(),...e}}setOperationName(e){this.operationName=e}setEndpoint(e){this.endpoint=e}setServiceUUID(e){this.serviceUUID=e}}const ue=fetch;let O=!1;async function B(t,e,n,a){try{const s=f();let i;try{i=JSON.stringify({query:n,variables:a,operationName:e})}catch{i=JSON.stringify({query:n,operationName:e})}O=!0,ue(t,{method:"POST",headers:{"Content-Type":"application/json"},body:i}).then(async r=>{if(O=!1,!r.ok)return void(s.sfDebug&&console.error(`GraphQL request failed with status ${r.status} for ${e}`));const o=await r.json();o.errors?.length?(function(u,m,p){const g=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0;console.error(g==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${p.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(m)} for operation key ${g}`)})(o.data,o.errors,s):s.sfDebug&&(function(u,m,p){const g=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0,d=u[g]||!1;g==="identifyServiceDetails"&&(p.setServiceIdentificationReceived(d),f().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${p.serviceUUID}; serviceIdentificationReceived=${g==="identifyServiceDetails"?d:"N/A"}`))})(o.data,0,s)}).catch(r=>{O=!1,s.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${e} to ${t}:`,r),r.cause&&console.error("[RequestUtils] Error cause:",r.cause))})}catch(s){O=!1,f().sfDebug&&console.error("Error sending data to GraphQL server:",s)}}function C(t,e){if(!t)return e;const n=t.toLowerCase();return n==="true"||n==="1"||n==="yes"}const D=new P.AsyncLocalStorage;let M=!1;function W(t,e){try{const n=JSON.stringify(t).length/1048576;return n<=e?t:{_truncated:!0,_originalSizeMB:n.toFixed(2),_limitMB:e,_preview:JSON.stringify(t).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof t}}}function _(t,e){const n=process.env[t];return n===void 0?e:n==="true"||n==="1"}function X(t,e){const n=process.env[t];if(n===void 0)return e;const a=parseFloat(n);return isNaN(a)?e:a}function x(){return{enabled:_("SF_WORKER_POOL_ENABLED",!0),trackFs:_("SF_WORKER_POOL_TRACK_FS",!1),trackDns:_("SF_WORKER_POOL_TRACK_DNS",!0),trackCrypto:_("SF_WORKER_POOL_TRACK_CRYPTO",!1),trackZlib:_("SF_WORKER_POOL_TRACK_ZLIB",!1),captureArguments:_("SF_WORKER_POOL_CAPTURE_ARGUMENTS",!0),captureReturnValue:_("SF_WORKER_POOL_CAPTURE_RETURN_VALUE",!0),argLimitMb:X("SF_WORKER_POOL_ARG_LIMIT_MB",1),returnLimitMb:X("SF_WORKER_POOL_RETURN_LIMIT_MB",1)}}function Y(t,e,n,a){let s;try{switch(t){case"fs":s=(function(i,r){const o={};switch(i){case"readFile":case"writeFile":case"appendFile":o.path=String(r[0]||""),r[1]&&typeof r[1]=="object"?(o.encoding=r[1].encoding||null,o.flag=r[1].flag||null):typeof r[1]=="string"&&(o.encoding=r[1]),i!=="writeFile"&&i!=="appendFile"||(Buffer.isBuffer(r[1])?(o.dataType="Buffer",o.dataSize=r[1].length):typeof r[1]=="string"&&(o.dataType="string",o.dataSize=r[1].length));break;case"readdir":case"stat":case"lstat":case"access":case"chmod":case"mkdir":case"rmdir":case"unlink":o.path=String(r[0]||""),r[1]&&typeof r[1]=="object"&&(o.options={...r[1]},delete o.options.callback);break;case"rename":o.oldPath=String(r[0]||""),o.newPath=String(r[1]||"");break;case"open":o.path=String(r[0]||""),o.flags=r[1],o.mode=r[2];break;case"close":case"fstat":o.fd=r[0];break;case"read":case"write":o.fd=r[0],Buffer.isBuffer(r[1])&&(o.bufferSize=r[1].length),o.offset=r[2],o.length=r[3],o.position=r[4];break;default:o.argsCount=r.length-1}return o})(e,n);break;case"dns":s=(function(i,r){const o={};switch(i){case"lookup":o.hostname=String(r[0]||""),typeof r[1]=="object"?(o.family=r[1].family,o.all=r[1].all):typeof r[1]=="number"&&(o.family=r[1]);break;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":o.hostname=String(r[0]||"");break;case"reverse":o.ip=String(r[0]||"");break;default:o.argsCount=r.length-1}return o})(e,n);break;case"crypto":s=(function(i,r){const o={};switch(i){case"pbkdf2":o.passwordType=typeof r[0],o.saltType=typeof r[1],o.iterations=r[2],o.keylen=r[3],o.digest=r[4];break;case"scrypt":o.passwordType=typeof r[0],o.saltType=typeof r[1],o.keylen=r[2],typeof r[3]=="object"&&(o.N=r[3].N,o.r=r[3].r,o.p=r[3].p);break;case"randomBytes":o.size=r[0];break;case"generateKeyPair":o.type=r[0],typeof r[1]=="object"&&(o.modulusLength=r[1].modulusLength,o.namedCurve=r[1].namedCurve);break;default:o.argsCount=r.length-1}return o})(e,n);break;case"zlib":s=(function(i,r){const o={};return Buffer.isBuffer(r[0])?(o.inputType="Buffer",o.inputSize=r[0].length):typeof r[0]=="string"?(o.inputType="string",o.inputSize=r[0].length):o.inputType=typeof r[0],r[1]&&typeof r[1]=="object"&&typeof r[1]!="function"&&(o.options={...r[1]}),o})(0,n);break;default:return null}return a>0?W(s,a):s}catch{return{error:"Failed to capture arguments",argsCount:n.length-1}}}function Z(t,e,n,a){let s;try{switch(t){case"fs":s=(function(i,r){if(!r)return null;switch(i){case"readFile":return Buffer.isBuffer(r)?{type:"Buffer",size:r.length}:typeof r=="string"?{type:"string",size:r.length}:{type:typeof r};case"readdir":return{count:Array.isArray(r)?r.length:0,items:r};case"stat":case"lstat":case"fstat":return{size:r.size,mode:r.mode,isFile:r.isFile(),isDirectory:r.isDirectory()};case"open":return{fd:r};case"read":return{bytesRead:r};case"write":return{bytesWritten:r};default:return r}})(e,n);break;case"dns":s=(function(i,r){if(!r)return null;switch(i){case"lookup":return Array.isArray(r)?{count:r.length,addresses:r}:r;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":return{count:Array.isArray(r)?r.length:0,records:r};case"reverse":return{hostnames:r};default:return r}})(e,n);break;case"crypto":s=(function(i,r){if(!r)return null;switch(i){case"pbkdf2":case"scrypt":case"randomBytes":return Buffer.isBuffer(r)?{type:"Buffer",size:r.length}:{type:typeof r};case"generateKeyPair":return{hasPublicKey:!!r?.publicKey,hasPrivateKey:!!r?.privateKey};default:return r}})(e,n);break;case"zlib":s=(function(i,r){return r?Buffer.isBuffer(r)?{type:"Buffer",size:r.length}:typeof r=="string"?{type:"string",size:r.length}:{type:typeof r}:null})(0,n);break;default:return null}return a>0?W(s,a):s}catch{return{error:"Failed to capture result",type:typeof n}}}function le(t){return t.operationType==="worker_pool"}class ne extends te{constructor(){super(),this.operationName="CollectFunctionSpans"}send(e){const n=f().sfDebug;n&&console.log(`[FunctionSpanTransmitter] Preparing to send ${e.length} function span(s)`);for(const a of e)try{if(le(a)){this.sendWorkerPoolSpan(a,n);continue}const s=a;let i;if(s.result!==void 0&&s.result!==null){const o=typeof s.result;i=JSON.stringify({type:o,has_value:!0,value:s.result})}else i=s.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const r=this.getVariables({library:"JS/TS BACKEND",version:f().version,spanId:s.spanId,parentSpanId:s.parentSpanId,filePath:s.filePath,lineNumber:s.metadata.line,columnNumber:s.metadata.column,functionName:s.functionName,arguments:JSON.stringify(s.args||{}),returnValue:i,startTimeNs:(1e6*Date.now()-1e6*s.duration).toString(),durationNs:(1e6*s.duration).toString()});n&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(r,null,2))),B(this.endpoint,this.operationName,this.getQuery(),r),n&&console.log(`[FunctionSpanTransmitter] Queued function span for ${s.functionName}`)}catch(s){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${a.functionName}:`,s)}}sendWorkerPoolSpan(e,n){try{let a;if(e.result!==void 0&&e.result!==null){const i=typeof e.result;a=JSON.stringify({type:i,has_value:!0,value:e.result})}else a=e.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const s=this.getVariables({library:"JS/TS BACKEND",version:f().version,spanId:e.spanId,operationName:e.operationName,moduleName:e.moduleName,methodName:e.methodName,startTimeNs:e.startTimeNs,durationNs:e.durationNs,arguments:JSON.stringify(e.args||{}),returnValue:a,error:e.error,pid:e.pid,threadId:e.threadId});n&&(console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${e.operationName}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(s,null,2))),B(this.endpoint,"CollectWorkerPoolSpans",this.getWorkerPoolQuery(),s),n&&console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${e.operationName}`)}catch(a){console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${e.operationName}:`,a)}}getWorkerPoolQuery(){return`
2
- mutation CollectWorkerPoolSpans(
3
- $apiKey: String!,
4
- $serviceUuid: String!,
5
- $sessionId: String!,
6
- $timestampMs: String!,
7
- $library: String!,
8
- $version: String!,
9
- $spanId: String!,
10
- $operationName: String!,
11
- $moduleName: String!,
12
- $methodName: String!,
13
- $startTimeNs: String!,
14
- $durationNs: String!,
15
- $parentSpanId: String,
16
- $arguments: String,
17
- $returnValue: String,
18
- $error: String,
19
- $pid: Int,
20
- $threadId: Int
21
- ) {
22
- collectWorkerPoolSpans(
23
- apiKey: $apiKey,
24
- serviceUuid: $serviceUuid,
25
- sessionId: $sessionId,
26
- timestampMs: $timestampMs,
27
- library: $library,
28
- version: $version,
29
- spanId: $spanId,
30
- operationName: $operationName,
31
- moduleName: $moduleName,
32
- methodName: $methodName,
33
- startTimeNs: $startTimeNs,
34
- durationNs: $durationNs,
35
- parentSpanId: $parentSpanId,
36
- arguments: $arguments,
37
- returnValue: $returnValue,
38
- error: $error,
39
- pid: $pid,
40
- threadId: $threadId
41
- )
42
- }
43
- `}getQuery(){return`
44
- ${this.queryType} ${this.operationName}(
45
- $apiKey: String!,
46
- $serviceUuid: String!,
47
- $sessionId: String!,
48
- $timestampMs: String!,
49
- $parentSpanId: String,
50
- $library: String!,
51
- $version: String!,
52
- $spanId: String!,
53
- $filePath: String!,
54
- $lineNumber: Int!,
55
- $columnNumber: Int!,
56
- $functionName: String!,
57
- $arguments: String!,
58
- $returnValue: String,
59
- $startTimeNs: String!,
60
- $durationNs: String!
61
- ) {
62
- ${this.queryName}(
63
- apiKey: $apiKey,
64
- serviceUuid: $serviceUuid,
65
- sessionId: $sessionId,
66
- timestampMs: $timestampMs,
67
- parentSpanId: $parentSpanId,
68
- library: $library,
69
- version: $version,
70
- spanId: $spanId,
71
- filePath: $filePath,
72
- lineNumber: $lineNumber,
73
- columnNumber: $columnNumber,
74
- functionName: $functionName,
75
- arguments: $arguments,
76
- returnValue: $returnValue,
77
- startTimeNs: $startTimeNs,
78
- durationNs: $durationNs
79
- )
80
- }
81
- `}}let V=null;function K(t){const e=T(),n=e?.sfDebug||!1;n&&console.log("[WorkerPool] Capturing span:",{operation:t.operationName,duration:`${t.duration}ms`,error:t.error,spanId:t.spanId,parentSpanId:t.parentSpanId}),process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
82
- ⚙️ Worker Pool Operation:`,{operation:t.operationName,duration:`${t.duration.toFixed(2)}ms`,arguments:t.args,result:t.error?`Error: ${t.error}`:t.result,spanId:t.spanId,parentSpanId:t.parentSpanId||"none"});const a=process.env.SF_FUNCSPAN_JSONL_FILE;if(a)try{const s=a==="true"||a==="1"?"funcspans.jsonl":a,i=Date.now(),r=process.hrtime.bigint(),o=BigInt(t.startTimeNs),u=Number(r-o)/1e6,m=new Date(i-u).toISOString(),p=JSON.stringify({timestamp:m,operationType:t.operationType,operationName:t.operationName,moduleName:t.moduleName,methodName:t.methodName,duration:t.duration,durationNs:t.durationNs,startTimeNs:t.startTimeNs,arguments:t.args,returnValue:t.error?{error:String(t.error)}:t.result,spanId:t.spanId,parentSpanId:t.parentSpanId,pid:t.pid,threadId:t.threadId})+`
83
- `;ae.appendFileSync(s,p,"utf-8")}catch(s){console.error("[WorkerPool] Error writing to JSONL file:",s)}if(n&&console.log("[WorkerPool] Sending span to transmitter"),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(V||(V=new ne),V).send([t]),n&&console.log("[WorkerPool] Span sent successfully")}catch(s){n&&console.error("[WorkerPool] Error sending span:",s)}}exports.BaseTransmitter=te,exports.ContextManager=y,exports.DEFAULT_DOMAINS_TO_EXCLUDE=re,exports.FunctionSpanTransmitter=ne,exports.captureWorkerPoolOperation=function(t,e,n,a,s){const i=T(),r=i?.sfDebug||!1;r&&console.log(`[WorkerPool] Capturing ${t}.${e}`);const o=x(),u=y.getInstance().getCurrentFunctionSpanId(),m=v();r&&console.log(`[WorkerPool] Span ID: ${m}, Parent: ${u||"none"}`);const p=new P.AsyncResource("WorkerPoolOperation"),g=process.hrtime.bigint();let d=null;o.captureArguments&&(d=Y(t,e,a,o.argLimitMb));const S=a.findIndex(b=>typeof b=="function");if(S===-1)return r&&console.log(`[WorkerPool] No callback found for ${t}.${e}`),n.apply(s,a);const N=a[S],$=[...a];return $[S]=function(b,...U){const k=process.hrtime.bigint()-g,G=Number(k)/1e6;N(b,...U),p.runInAsyncScope(()=>{r&&console.log(`[WorkerPool] ${t}.${e} completed in ${G.toFixed(3)}ms (${k}ns)`);let H=null,z=null;b?z=b?.message||String(b):o.captureReturnValue&&U.length>0&&(H=Z(t,e,U[0],o.returnLimitMb)),K({operationType:"worker_pool",operationName:`${t}.${e}`,moduleName:t,methodName:e,duration:G,durationNs:k.toString(),startTimeNs:g.toString(),args:d,result:H,error:z,spanId:m,parentSpanId:u,pid:process.pid,threadId:L.threadId})}),p.emitDestroy()},n.apply(s,$)},exports.captureWorkerPoolPromiseOperation=function(t,e,n,a,s){const i=T(),r=i?.sfDebug||!1;r&&console.log(`[WorkerPool] Capturing ${t}.${e} (Promise)`);const o=x(),u=y.getInstance().getCurrentFunctionSpanId(),m=v();r&&console.log(`[WorkerPool] Span ID: ${m}, Parent: ${u||"none"}`);const p=process.hrtime.bigint();let g=null;return o.captureArguments&&(g=Y(t,e,a,o.argLimitMb)),n.apply(s,a).then(d=>{const S=process.hrtime.bigint()-p,N=Number(S)/1e6;r&&console.log(`[WorkerPool] ${t}.${e} completed in ${N.toFixed(3)}ms (${S}ns)`);let $=null;return o.captureReturnValue&&($=Z(t,e,d,o.returnLimitMb)),K({operationType:"worker_pool",operationName:`${t}.${e}`,moduleName:t,methodName:e,duration:N,durationNs:S.toString(),startTimeNs:p.toString(),args:g,result:$,error:null,spanId:m,parentSpanId:u,pid:process.pid,threadId:L.threadId}),d},d=>{const S=process.hrtime.bigint()-p,N=Number(S)/1e6;throw r&&console.log(`[WorkerPool] ${t}.${e} failed in ${N.toFixed(3)}ms: ${d?.message||d}`),K({operationType:"worker_pool",operationName:`${t}.${e}`,moduleName:t,methodName:e,duration:N,durationNs:S.toString(),startTimeNs:p.toString(),args:g,result:null,error:d?.message||String(d),spanId:m,parentSpanId:u,pid:process.pid,threadId:L.threadId}),d})},exports.clearFuncspanOverride=function(){},exports.funcspanOverrideStorage=D,exports.getConfig=f,exports.getCurrentFunctionSpanId=function(){return y.getInstance().getCurrentFunctionSpanId()},exports.getDefaultConfig=function(){return{capture_arguments:!1,capture_return_value:!1,arg_limit_mb:1,return_limit_mb:1,autocapture_all_child_functions:!1,sample_rate:0,enable_sampling:!1,capture_sf_veritas:!1,parse_json_strings:!1}},exports.getEnvConfig=function(){return{capture_arguments:C(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:C(process.env.SF_FUNCSPAN_CAPTURE_RETURN_VALUE,!0),arg_limit_mb:parseInt(process.env.SF_FUNCSPAN_ARG_LIMIT_MB||"1",10),return_limit_mb:parseInt(process.env.SF_FUNCSPAN_RETURN_LIMIT_MB||"1",10),autocapture_all_child_functions:C(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:C(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:C(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:C(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}},exports.getFuncspanOverride=function(){if(M)return D.getStore();try{M=!0;const t=D.getStore(),e=new Error().stack?.split(`
84
- `).slice(1,4).join(`
85
- `);return console.log(`[getFuncspanOverride] Called from:
86
- ${e}`),console.log("[getFuncspanOverride] Returned value:",t),t}catch(t){return void console.error("[getFuncspanOverride] ❌ Error:",t)}finally{M=!1}},exports.getGlobalConfigUnsafe=T,exports.getOrCreateConfig=function(t){const e=T();if(e)return{config:e};const n=new ce(t);return(function(a){globalThis[ee]=a})(n),n.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",n),{config:n}},exports.isModuleTrackingEnabled=function(t){const e=x();if(!e.enabled)return!1;switch(t){case"fs":return e.trackFs;case"dns":return e.trackDns;case"crypto":return e.trackCrypto;case"zlib":return e.trackZlib;default:return!1}},exports.mergeConfigs=function(...t){const e={};for(const n of t)for(const a in n)n[a]!==void 0&&(e[a]=n[a]);return e},exports.nonBlockingPost=B,exports.parseHeaderOverride=function(t){try{const e=t.split("-");return e.length!==9?(console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${e.length}`),null):{capture_arguments:e[0]==="1",capture_return_value:e[1]==="1",arg_limit_mb:parseInt(e[2],10),return_limit_mb:parseInt(e[3],10),autocapture_all_child_functions:e[4]==="1",sample_rate:parseFloat(e[5]),enable_sampling:e[6]==="1",capture_sf_veritas:e[7]==="1",parse_json_strings:e[8]==="1"}}catch(e){return console.error(`[FuncSpan] Failed to parse header override "${t}":`,e),null}},exports.runWithContext=function(t){const e={...y.getInstance().getCurrentContext()};F.run(e,()=>{t()})},exports.setFuncspanOverride=function(t){D.enterWith(t)},exports.truncateToLimit=W,exports.v4=v;