@sailfish-ai/sf-veritas 0.2.6 → 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.
- package/dist/contextManager-CEPhVu9T.js +197 -0
- package/dist/contextManager-CGINtRN5.cjs +1 -0
- package/dist/funcSpanTransformer-B9WWl-g1.cjs +1 -0
- package/dist/funcSpanTransformer-CWNEWRxq.js +225 -0
- package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
- package/dist/plugins/funcspanEsbuildPlugin.mjs +17 -11
- package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
- package/dist/plugins/funcspanRollupPlugin.mjs +13 -8
- package/dist/plugins/funcspanTscPlugin.cjs +1 -1
- package/dist/plugins/funcspanTscPlugin.mjs +19 -14
- package/dist/plugins/funcspanVitePlugin.cjs +1 -1
- package/dist/plugins/funcspanVitePlugin.mjs +15 -10
- package/dist/plugins/funcspanWebpackLoader.cjs +1 -1
- package/dist/plugins/funcspanWebpackLoader.mjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
- package/dist/plugins/funcspanWebpackPlugin.mjs +22 -17
- package/dist/runtime/funcspanRegister.cjs +276 -0
- package/dist/runtimeConfig-CpQ27dZD.cjs +8 -0
- package/dist/runtimeConfig-emBNO3lJ.js +350 -0
- package/dist/sf-veritas.cjs +18 -18
- package/dist/sf-veritas.mjs +461 -620
- package/dist/source-map-Cr6YkjTd.js +631 -0
- package/dist/source-map-rHHEdpre.cjs +1 -0
- package/dist/types/dataTransmitter.d.ts +1 -0
- package/dist/types/funcSpanConfig.d.ts +8 -0
- package/dist/types/funcSpanConfigLoader.d.ts +10 -0
- package/dist/types/index.d.ts +4 -2
- package/dist/types/logHandler.d.ts +5 -0
- package/dist/types/plugins/funcSpanTransformer.d.ts +13 -0
- package/dist/types/runtime/instrumentationDetector.d.ts +33 -0
- package/dist/types/runtime/runtimeConfig.d.ts +48 -0
- package/dist/types/sourceLocation.d.ts +30 -0
- package/dist/types/unifiedInterceptor.d.ts +4 -0
- package/dist/worker-pool-capture.cjs +1 -1
- package/dist/worker-pool-capture.mjs +1 -1
- package/dist/workerPoolSpanCapture-B5KN-q4b.js +528 -0
- package/dist/workerPoolSpanCapture-Dg_WGjmO.cjs +86 -0
- package/package.json +5 -2
- package/dist/funcSpanTransformer-TjdooSrw.cjs +0 -1
- package/dist/funcSpanTransformer-sqmZLAcs.js +0 -750
- package/dist/workerPoolSpanCapture-BOnYC4s3.js +0 -705
- package/dist/workerPoolSpanCapture-CNEouInA.cjs +0 -83
package/dist/sf-veritas.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var I=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./contextManager-CGINtRN5.cjs"),p=require("./workerPoolSpanCapture-Dg_WGjmO.cjs"),h=require("./runtimeConfig-CpQ27dZD.cjs"),le=require("node:module"),W=require("fs"),ue=require("./source-map-rHHEdpre.cjs"),pe=require("path"),ge=require("glob"),E=require("worker_threads"),O=require("./funcSpanTransformer-B9WWl-g1.cjs");var L=typeof document<"u"?document.currentScript:null;function ae(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 k=ae(W),$=ae(pe);class N 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
|
-
`,
|
|
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 fe(n){try{return JSON.stringify(n),!0}catch{return!1}}class he extends p.BaseTransmitter{constructor(){super();I(this,"serviceIdentifier",new N);this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,o,r,i){this.sendAppIdentifier(),this.send(t,o,r,i)}async send(t,o,r,i){if(!o&&!i)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let l=[];if(!i){const d=(function(a){const u={},f=[];if(a)for(const[m,y]of Object.entries(a))fe(y)?u[m]=y:f.push(m);return{traitsJson:JSON.stringify(u),excludedFields:f}})(o);i=d.traitsJson,l=d.excludedFields}const s=this.getVariables({userId:t,traitsJson:i,excludedFields:l,override:r,library:c.getConfig().packageLibraryType,version:c.getConfig().version});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),s)}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 z{constructor(e){I(this,"metadataTransmitter");this.apiKey=e,this.metadataTransmitter=new he}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 K extends p.BaseTransmitter{constructor(){super();I(this,"serviceIdentifier",new N)}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){try{const o=Array.isArray(t)?t:[t,"default",null,null],r=this.getVariables({contents:o[0],level:o[1],sourceFile:o[2]||void 0,sourceLine:o[3]||void 0});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),r)}catch(o){c.getConfig().sfDebug&&console.error("🚨 Error in send():",o)}}getQuery(){return`
|
|
30
30
|
${this.queryType} ${this.operationName}(
|
|
31
31
|
$apiKey: String!,
|
|
32
32
|
$serviceUuid: String!,
|
|
@@ -34,7 +34,9 @@
|
|
|
34
34
|
$timestampMs: String!,
|
|
35
35
|
$level: String!,
|
|
36
36
|
$contents: String!,
|
|
37
|
-
$parentSpanId: String
|
|
37
|
+
$parentSpanId: String,
|
|
38
|
+
$sourceFile: String,
|
|
39
|
+
$sourceLine: Int
|
|
38
40
|
) {
|
|
39
41
|
${this.queryName}(
|
|
40
42
|
apiKey: $apiKey,
|
|
@@ -43,14 +45,12 @@
|
|
|
43
45
|
timestampMs: $timestampMs,
|
|
44
46
|
level: $level,
|
|
45
47
|
contents: $contents,
|
|
46
|
-
parentSpanId: $parentSpanId
|
|
48
|
+
parentSpanId: $parentSpanId,
|
|
49
|
+
sourceFile: $sourceFile,
|
|
50
|
+
sourceLine: $sourceLine
|
|
47
51
|
)
|
|
48
52
|
}
|
|
49
|
-
`}}const G={};class F{constructor({file:e,line:n,function:i,code:t,locals:s={},offender:l=!1,column:a}){A(this,"file");A(this,"line");A(this,"function");A(this,"code");A(this,"locals");A(this,"offender");A(this,"column");this.file=e,this.line=n,this.function=i,this.code=t,this.locals=s,this.offender=l,this.column=a}toDict(){const e={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([n,i])=>[n,String(i)]))};return this.offender&&(e.offender=this.offender),this.column!==void 0&&(e.column=this.column),e}toJson(){return JSON.stringify(this.toDict())}}class R{static encode(e){return e instanceof F?e.toDict():Array.isArray(e)?e.map(n=>R.encode(n)):typeof e=="object"&&e!==null?JSON.stringify(e):e}static stringify(e){return JSON.stringify(R.encode(e),(n,i)=>i instanceof F?i.toDict():i)}}let B,W=0;function fe(o){r.getConfig().sfDebug&&console.log("Initializing Exception Interceptor...");try{const a=(function(){if(B!==void 0)return B;const g=process.env||{},c=Q(g.SF_IS_LOCAL);if(c!==void 0)return B=c;const d=(g.SF_ENV||g.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(d))return B=!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(p=>!!g[p]))return B=!1;const I=(G.hostname?.()||g.HOSTNAME||"").toLowerCase();return I==="localhost"||I.endsWith(".local")||I.includes("local")?B=!0:B=!1})();o?.setSupplementalFields?.({isFromLocalService:a}),(async function(g){if(M)return;M=!0;const c=process.env||{};if(Q(c.SF_IS_LOCAL)===void 0)try{await(async function(d){const I=U("http://169.254.169.254/latest/meta-data/",{},d),p=U("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},d),C=U("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},d);return(await Promise.allSettled([I,p,C])).some(u=>u.status==="fulfilled"&&(u.value==="ok"||u.value==="http_error"))})(150)&&B&&(B=!1,g?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(o).catch(()=>{})}catch{}const e=new N.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB1bmRlZmluZWQ7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB1bmRlZmluZWQ7CgovKioKICogUHJvY2Vzc2VzIGNhbGwgZnJhbWVzIGZyb20gYW4gZXhjZXB0aW9uIGFuZCBwb3N0cyB0aGVtIHZpYSB0aGUgV29ya2Vy4oCZcyBwYXJlbnRQb3J0LgogKgogKiBAcGFyYW0gc2Vzc2lvbiAtIFRoZSBEZXZUb29scyBzZXNzaW9uIG9yIHNpbWlsYXIgb2JqZWN0IHlvdSB1c2UgdG8gcXVlcnkgZm9yIHNjcmlwdCBzb3VyY2VzLgogKiBAcGFyYW0gY2FsbEZyYW1lcyAtIEFuIGFycmF5IG9mIGNhbGwgZnJhbWUgb2JqZWN0cy4KICogQHBhcmFtIGRlc2NyaXB0aW9uTGluZXMgLSBBbiBhcnJheSBvZiBsaW5lcyBmcm9tIHRoZSBlcnJvcuKAmXMgZGVzY3JpcHRpb24sIGVhY2ggdHlwaWNhbGx5IGJlZ2lubmluZyB3aXRoICJhdCAiLgogKiBAcmV0dXJucyB7UHJvbWlzZTx2b2lkPn0KICovCmV4cG9ydCBhc3luYyBmdW5jdGlvbiBwcm9jZXNzQ2FsbEZyYW1lcyhzZX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lsZSA9IGRlc2NyaXB0aW9uTGluZXNbaW5kZXhdLnRyaW0oKTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgZmlsZSA9ICI8dW5rbm93bj4iOwogICAgICAgIH0KCiAgICAgICAgLy8gSWYgd2UgaGF2ZSBhIHZhbGlkIGxvY2F0aW9uIGFuZCBzY3JpcHRJZCwgZmV0Y2ggdGhlIGNvZGUgbGluZQogICAgICAgIGlmIChsb2NhdGlvbiAmJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHsgc2NyaXB0U291cmNlIH0gPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgIkRlYnVnZ2VyLmdldFNjcmlwdFNvdXJjZSIsCiAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IiwKICAgICAgICB9OwogICAgICB9CiAgICB9KSwKICApOwogIC8vIFBvc3QgZXhjZXB0aW9uIGRhdGEKICBwYXJlbnRQb3J0Py5wb3N0TWVzc2FnZSh7IHR5cGU6ICJleGNlcHRpb24iLCBmcmFtZXMgfSk7Cn0KCi8qKgogKiBIYW5kbGVzIHRoZSAicGF1c2VkIiBzdGF0ZSBvZiB0aGUgZGVidWdnZXIgYW5kIHByb2Nlc3NlcyBleGNlcHRpb25zIG9yIHByb21pc2UgcmVqZWN0aW9ucy4KICogQHBhcmFtIHtTZXNzaW9ufSBzZXNzaW9uIC0gVGhlIGRlYnVnZ2luZyBzZXNzaW9uIGluc3RhbmNlLg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0SWQ7CiAgICAgICAgICBhd2FpdCB1bnJvbGxPYmplY3Qoc2Vzc2lvbiwgaWQsIHByb3AubmFtZSwgdmFyaWFibGVzKTsKICAgICAgICB9IGVsc2UgaWYgKHByb3A/LnZhbHVlKSB7CiAgICAgICAgICB1bnJvbGxPdGhlcihwcm9wLCB2YXJpYWJsZXMpOwogICAgICAgIH0KICAgICAgfQogICAgICByZXR1cm4gdmFyaWFibGVzOwogICAgfQogIH0gY2F0Y2ggKGVycikgewogICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBsb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+IHsKICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlcjoiLCBlcnJvcik7CiAgfQp9KTsKCi8vIEtlZXAgdGhlIHdvcmtlciBhbGl2ZQpzZXRJbnRlcnZhbCgoKSA9PiB7fSwgMTAwMDApOwo="),{workerData:{captureAllExceptions:!0}});let n=null;const i=new WeakMap;e.on("message",a=>{if(typeof a=="string"&&r.getConfig().sfDebug&&console.log(`[Worker] ${a}`),a.readyToGetParameters&&e.postMessage({sfDebug:r.getConfig().sfDebug,stackDepthLocals:r.getConfig().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:r.getConfig().nodeModulesToCollectLocalVariablesOn}),a.type==="exception"){const{frames:g}=a,c=n;if(!c)return;const d=i.get(c),I=(function(C){return C?C.split(`
|
|
50
|
-
`).slice(1).map(u=>{const m=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(u)||/at (.+):(\d+):(\d+)/.exec(u);if(m){const[,h,Z,b,y]=m;return new F({function:h||"<anonymous>",locals:{},file:Z||"<unknown>",line:parseInt(b,10)||0,code:"<not captured>",column:parseInt(y)||0})}return new F({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(c.stack),p=(function(C,u){const m=[];let h=-1,Z=-1;for(let b=0;b<C.length;b++){const y=Ze(C[b].file);if(Z=b,y!=="<unknown>"){for(let f=0;f<u.length;f++){const v=u[f];if(Ie(v,y)||typeof v.file=="string"&&v.file.includes(y)){h=f,W=0,r.getConfig().sfDebug&&console.log(`✅ Matched Frame Found: ${y} @ Debugger Frame ${f}`);break}}if(h!==-1)break}}if(h===-1)return W===10?(W=0,C):(++W,r.getConfig().sfDebug&&console.log(`"❌ No matching frame found. Checking once again, Attempt N ${W}"`),[]);r.getConfig().sfDebug&&console.log(`🔄 Merging from matched index ${h} onward...`);for(let b=0;b<u.length;b++){const y=C[Z+b],f=u[h+b];m.push(new F({function:f?.function||y?.function||"<anonymous>",locals:f?.locals||y?.locals||{},file:y?.file||f?.file||"<unknown>",line:f?.line||y?.line||0,code:f?.code||y?.code||"<not captured>"}))}return m})(I,g||[]);if(p.length!==0){n=null;const C=r.getConfig().stackDepthCodeTraceDepth,u=C===-1?p:p.slice(0,C+1),m=Math.min(u.length,I.length);for(let y=0;y<m;y++)(async()=>{const f=ye(u[y].file,I[y].line,I[y].column);f&&(f.content!=null&&(u[y].code=f.content),f.file!=null&&(u[y].file=f.file))})();o.setOperationName("CollectExceptions");const h=c.message?`${c.name}: ${c.message}`:c.name;r.getConfig().sfDebug&&console.log("error message is : ",h);const Z=r.ContextManager.getInstance(),b=i.get(c);b?(Z.setTraceIdFor(b,b),Z.runWithSession(b,()=>{Z.setTraceId(b),o.doSend(h,u)})):o.doSend(h,u),d?r.ContextManager.getInstance().runWithSession(d,()=>{o.doSend(h,u)}):o.doSend(h,u)}}}),e.on("error",a=>{console.error("[Worker Error]",a)}),e.on("exit",a=>{console.error(`[Worker] Exited with code ${a}`)}),e.unref();const t=Error,s=new Set;function l(...a){const g=Reflect.construct(t,a);Reflect.setPrototypeOf(g,l.prototype);try{const d=r.ContextManager.getInstance().getTraceId();i.set(g,d)}catch{}t.captureStackTrace&&t.captureStackTrace(g,l);const c=`${g.message}:${g.stack?.split(`
|
|
51
|
-
`)[1]?.trim()}`;if(!s.has(c)){s.add(c),n=g;const d=r.ContextManager.getInstance().getTraceId();i.set(g,d),e.postMessage({type:"processException",error:g.message})}return g}l.prototype=Object.create(t.prototype,{constructor:{value:l,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(l,t),globalThis.Error=l}function j(o){return o=(o=(o=o.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function ye(o,e,n){const i=(function(s){s.startsWith("at ")&&(s=s.slice(3).trim());const l=s.match(/^(.*?)(:\d+)+(\.map)?$/);return l?l[1]:s})(o);if(!i||i==="<unknown>")return null;const t=i+".map";try{const s=X.readFileSync(t,"utf-8");if(s){const l=JSON.parse(s);let a=new D.sourceMapExports.SourceMapConsumer(l).originalPositionFor({line:e,column:n});if(i&&a.source){const g=j(i),c=l.sources.findIndex(d=>j(d)===g);if(c===-1)r.getConfig().sfDebug&&console.log(`Source file "${i}" not found in the source map.`);else{const d=l.sourcesContent[c],I=l.names.join(",");if(d)return{content:d.split(`
|
|
52
|
-
`).slice(a.line-1,a.line+20).join(`
|
|
53
|
-
`),name:I,file:a.source};r.getConfig().sfDebug&&console.log(`No source content available for file "${i}".`)}}return{content:l.sourcesContent[0],name:l.names[0],file:l.file}}}catch(s){r.getConfig().sfDebug&&console.log(`Cant read/parse "${t}: Error - ".`,s)}return null}function Ze(o){return o?.split("/").pop()||"<unknown>"}function Ie(o,e){if(!o||typeof o!="object")return!1;for(const n of Object.values(o))if(typeof n=="string"&&n.includes(e)||typeof n=="object"&&Ie(n,e))return!0;return!1}let M=!1;function Q(o){if(!o)return;const e=o.toLowerCase().trim();return!!["1","true","yes","on"].includes(e)||!["0","false","no","off"].includes(e)&&void 0}function U(o,e,n){return new Promise(i=>{try{const t=new URL(o),s=(t.protocol,G).request({method:"GET",hostname:t.hostname,port:t.port||(t.protocol==="https:"?443:80),path:t.pathname+(t.search||""),headers:e},l=>{l.resume(),l.statusCode&&l.statusCode>=200&&l.statusCode<400?i("ok"):i("http_error")});s.on("error",()=>i("error")),s.setTimeout(n,()=>{s.destroy(),i("timeout")}),s.end()}catch{i("error")}})}class Se extends r.BaseTransmitter{constructor(){super();A(this,"serviceIdentifier",new V);A(this,"supplementalFields",{});this.setOperationName("CollectExceptions")}setSupplementalFields(n){this.supplementalFields={...this.supplementalFields,...n}}normalizedSupplementalForGraphQL(){const{isFromLocalService:n}=this.supplementalFields,i={};return n!==void 0&&(i.isFromLocalService=n),i}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(n,i){this.sendAppIdentifier(),this.send(n,i)}async send(n,i){r.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const t=JSON.stringify(R.encode(i)),s=this.normalizedSupplementalForGraphQL(),l=this.getVariables({exceptionMessage:n,traceJson:t,reentrancyGuardPreactive:!1,library:r.getConfig().packageLibraryType,version:r.getConfig().version,...s});r.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),l)}getQuery(){return`
|
|
53
|
+
`}}class me extends p.BaseTransmitter{constructor(){super();I(this,"serviceIdentifier",new N);I(this,"supplementalFields",{});this.setOperationName("CollectExceptions")}setSupplementalFields(t){this.supplementalFields={...this.supplementalFields,...t}}normalizedSupplementalForGraphQL(){const{isFromLocalService:t}=this.supplementalFields,o={};return t!==void 0&&(o.isFromLocalService=t),o}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,o){this.sendAppIdentifier(),this.send(t,o)}async send(t,o){c.getConfig().sfDebug&&console.log(" SENDING EXCEPTION...");const r=JSON.stringify(h.CustomJSONEncoderForFrameInfo.encode(o)),i=this.normalizedSupplementalForGraphQL(),l=this.getVariables({exceptionMessage:t,traceJson:r,reentrancyGuardPreactive:!1,library:c.getConfig().packageLibraryType,version:c.getConfig().version,...i});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),l)}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 P=(n=>(n.UNKNOWN="unknown",n.ANONYMOUS="anonymous",n.NOT_CAPTURED="not captured",n))(P||{});const R="http:",A="https:",Se=le.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:L&&L.tagName.toUpperCase()==="SCRIPT"&&L.src||new URL("sf-veritas.cjs",document.baseURI).href);let V=!1;function ye(){const n=c.getConfig().sfDebug;if(V)return void(n&&h.internalLog("[patchNodeHttpInbound] Already installed, skipping."));let e;V=!0;try{e=Se("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[_,v]of Object.entries(g))v!=null&&(Array.isArray(v)?S[_.toLowerCase()]=v.join(", "):S[_.toLowerCase()]=String(v));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 Ie extends K{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
|
-
`,
|
|
93
|
+
`,o={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};p.nonBlockingPost(this.endpoint,this.operationName,t,o)}}class _e extends p.BaseTransmitter{constructor(){super();I(this,"serviceIdentifier",new N);this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){const{name:o,column:r,line:i,entrypoint:l,retryWithoutTraceId:s}=t,d=this.getVariables({name:o,column:r,line:i,entrypoint:l,retryWithoutTraceId:s});p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),d)}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 ve extends p.BaseTransmitter{constructor(){super();I(this,"serviceIdentifier",new N);this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}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),
|
|
124
|
+
`}async send(t){const o={data:{...t}};await p.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}}const q=[400,403];class $e{constructor(e=[]){I(this,"HEADER_TRACING","X-Sf3-Rid");I(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");I(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");I(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");I(this,"contextManager");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(W.readFileSync(i,"utf-8"));let s=(await new ue.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()||P.UNKNOWN,column:m.column?.toString()||P.NOT_CAPTURED,name:m.name||P.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&&q.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:_,pageVisitId:v,requestId:b}=this.extractIdsFromTraceHeader(l);return t.doSend({apiKey:c.getConfig().apiKey,requestId:b,pageVisitId:v,recordingSessionId:_,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||R,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||R,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=R));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)&&q.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||A,hostname:a.hostname,path:a.pathname+a.search,headers:{}}}else i instanceof URL?s={protocol:i.protocol||A,hostname:i.hostname,path:i.pathname+i.search,headers:{}}:(s={...i},s.protocol||(s.protocol=A));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)&&q.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(),console.log(`[RequestInterceptor] Patched ${t}`)}catch(o){console.warn(`[RequestInterceptor] Could not patch ${t}: ${o.message}`)}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class be extends K{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
|
-
`,n=this.getVariables({serviceIdentifier:r.getConfig().serviceIdentifier,serviceVersion:r.getConfig().serviceVersion,serviceAdditionalMetadata:r.getConfig().serviceAdditionalMetadata,gitSha:r.getConfig().gitSha||""});r.nonBlockingPost(this.endpoint,this.operationName,e,n)}}class Ve{constructor(e=[process.cwd()],n=!1){A(this,"rootPaths");A(this,"fileConfigs",new Map);A(this,"functionConfigs",new Map);A(this,"directoryConfigs",new Map);A(this,"hasSailfishFiles",!1);A(this,"debug");this.rootPaths=e,this.debug=n||process.env.SF_DEBUG==="true"}async loadAllConfigs(){this.debug&&console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:",this.rootPaths);const e=[];for(const n of this.rootPaths)T.existsSync(n)?await this._walkDirectory(n,e):this.debug&&console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${n}`);e.length>0?(this.hasSailfishFiles=!0,this.debug&&(console.log(`[FuncSpan ConfigLoader] Found ${e.length} .sailfish files:`),e.forEach(n=>console.log(`[FuncSpan ConfigLoader] - ${n}`)))):this.debug&&console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");for(const n of e)await this._loadConfigFile(n);await this._resolveInheritance(),this.debug&&console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`)}getConfig(e,n){const i=this.hasSailfishFiles?r.getEnvConfig():r.getDefaultConfig(),t=this._getDirectoryConfig(e),s=S.normalize(e),l=this.fileConfigs.get(s)||{};let a={};if(n){const g=this.functionConfigs.get(s);g&&(a=g.get(n)||{})}return r.mergeConfigs(i,t,l,a)}async _walkDirectory(e,n){try{const i=T.readdirSync(e,{withFileTypes:!0});for(const t of i){const s=S.join(e,t.name);t.isFile()&&t.name===".sailfish"?n.push(s):t.name==="node_modules"||t.isDirectory()&&t.name.startsWith(".")&&t.name!==".sailfish"||t.isDirectory()&&await this._walkDirectory(s,n)}}catch(i){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,i)}}async _loadConfigFile(e){try{const n=T.readFileSync(e,"utf-8"),i=S.dirname(e);let t=null;try{t=JSON.parse(n)}catch{try{t=require("js-yaml").load(n)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,s))}}if(!t)return;t.default&&this.directoryConfigs.set(i,t.default),t.files&&await this._expandFileGlobs(i,t.files,t.default||{}),t.functions&&this._storeFunctionConfigs(i,t.functions,t.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${i}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!t.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(t.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(t.functions||{}).length}`))}catch(n){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,n)}}async _expandFileGlobs(e,n,i){for(const[t,s]of Object.entries(n))try{const l=S.join(e,t),a=await he.glob(l,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${t}' matched ${a.length} files`);for(const g of a){const c=S.normalize(g),d=r.mergeConfigs(i,s);this.fileConfigs.set(c,d),this.debug&&a.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${g}`)}}catch(l){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${t}':`,l)}}_storeFunctionConfigs(e,n,i){for(const[t,s]of Object.entries(n)){const l=t.split("::");if(l.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${t}' (expected format: 'file.ts::functionName')`);continue}const[a,g]=l,c=S.normalize(S.join(e,a));this.functionConfigs.has(c)||this.functionConfigs.set(c,new Map);const d=this.functionConfigs.get(c),I=r.mergeConfigs(i,s);d.set(g,I),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${c}::${g}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let n=S.dirname(S.normalize(e));const i=[];for(;n&&n!==S.dirname(n);){const t=this.directoryConfigs.get(n);t&&i.unshift(t),n=S.dirname(n)}return i.reduce((t,s)=>r.mergeConfigs(t,s),{})}}let w=null;async function ne(o,e){w=new Ve(o,e),await w.loadAllConfigs()}function te(o,e){return w?w.getConfig(o,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),r.getEnvConfig())}function oe(){return w!==null}const He=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],ie=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Ye=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Re=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let re=!1,se=!1;function Xe(){if(!se)try{const o=require("node:dns");if(o.__sf_worker_pool_patched__)return;Object.defineProperty(o,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of ie)if(typeof o[e]=="function"){const n=o[e];o[e]=function(...i){const t=i[0];return typeof t=="string"&&(t==="localhost"||t==="127.0.0.1")?n.apply(this,i):typeof i[i.length-1]=="function"?r.captureWorkerPoolOperation("dns",e,n,i,this):n.apply(this,i)},Object.defineProperty(o[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 n of ie)if(typeof e.promises[n]=="function"){const i=e.promises[n];e.promises[n]=function(...t){const s=t[0];return typeof s!="string"||s!=="localhost"&&s!=="127.0.0.1"?r.captureWorkerPoolPromiseOperation("dns",n,i,t,this):i.apply(this,t)},Object.defineProperty(e.promises[n],"name",{value:n,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(o),se=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(o){console.error("[WorkerPool] Error patching dns module:",o)}}let ae=!1,ce=!1,L=!1;function ge(){if(L)return;const o=process.env.SF_DEBUG==="true";o&&console.log("[WorkerPool] Initializing worker pool patching..."),r.isModuleTrackingEnabled("fs")&&(o&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!re)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const n of He)if(typeof e[n]=="function"){const i=e[n];e[n]=function(...t){return typeof t[t.length-1]=="function"?r.captureWorkerPoolOperation("fs",n,i,t,this):i.apply(this,t)},Object.defineProperty(e[n],"name",{value:n,writable:!1})}re=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),r.isModuleTrackingEnabled("dns")&&(o&&console.log("[WorkerPool] Patching dns module..."),Xe()),r.isModuleTrackingEnabled("crypto")&&(o&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!ae)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 n of Ye)if(typeof e[n]=="function"){const i=e[n];e[n]=function(...t){return typeof t[t.length-1]=="function"?r.captureWorkerPoolOperation("crypto",n,i,t,this):i.apply(this,t)},Object.defineProperty(e[n],"name",{value:n,writable:!1})}ae=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),r.isModuleTrackingEnabled("zlib")&&(o&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!ce)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 n of Re)if(typeof e[n]=="function"){const i=e[n];e[n]=function(...t){return typeof t[t.length-1]=="function"?r.captureWorkerPoolOperation("zlib",n,i,t,this):i.apply(this,t)},Object.defineProperty(e[n],"name",{value:n,writable:!1})}ce=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),L=!0,o&&console.log("[WorkerPool] Worker pool patching initialized")}function le(){return L}let $=null;function H(o){const e=r.getGlobalConfigUnsafe(),n=e?.sfDebug||!1;n&&console.log("[FuncSpan] captureSpanData called for:",{function:o.functionName,file:o.filePath,duration:`${o.duration}ms`,async:o.async,error:o.error,spanId:o.spanId});const i={functionName:o.functionName,filePath:o.filePath,metadata:o.metadata,args:o.args,result:o.result,error:o.error,duration:o.duration,durationNs:o.durationNs,async:o.async,spanId:o.spanId,parentSpanId:o.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
|
|
146
|
-
📊 Function Span:`,{function:`${
|
|
147
|
-
`;
|
|
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(`
|
|
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
|
+
`;W.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{(x||(x=new p.FunctionSpanTransmitter),x).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=O.setSkipTypeScriptPlugin,exports.transformFunctionSpans=O.transformFunctionSpans,exports.transformFunctionSpansSync=O.transformFunctionSpansSync,exports.addOrUpdateMetadata=function(n,e={},t,o=!1){const r=c.getConfig();new z(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,_){const v=p.getFuncspanOverride();if(v){const b=p.parseHeaderOverride(v);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${S}::${_}`),b}try{return X(S,_)}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.length&&(g[S]=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(C=>{const T=process.hrtime.bigint(),w=Date.now(),U=Number(T-m);let j=null;return d.capture_return_value&&d.return_limit_mb>0&&(j=p.truncateToLimit(C,d.return_limit_mb)),D({functionName:e,filePath:t,metadata:o,args:g,result:j,error:null,duration:w-y,durationNs:U,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),C},C=>{const T=process.hrtime.bigint(),w=Date.now(),U=Number(T-m);throw D({functionName:e,filePath:t,metadata:o,args:g,result:null,error:C?.message||String(C),duration:w-y,durationNs:U,startTimeNs:m.toString(),async:!0,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),C});const _=process.hrtime.bigint(),v=Date.now(),b=Number(_-m);let B=null;return d.capture_return_value&&d.return_limit_mb>0&&(B=p.truncateToLimit(S,d.return_limit_mb)),D({functionName:e,filePath:t,metadata:o,args:g,result:B,error:null,duration:v-y,durationNs:b,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.threadId}),u?a.setCurrentFunctionSpanId(u):a.clearCurrentFunctionSpanId(),S}catch(S){const _=process.hrtime.bigint(),v=Date.now(),b=Number(_-m);throw D({functionName:e,filePath:t,metadata:o,args:g,result:null,error:S?.message||String(S),duration:v-y,durationNs:b,startTimeNs:m.toString(),async:!1,spanId:f,parentSpanId:u,pid:process.pid,threadId:E.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=X,exports.identify=function(n,e,t,o=!1){const r=c.getConfig();new z(r.apiKey).identify(n,e,t,o)},exports.initializeConfigLoader=Q,exports.initializeWorkerPoolPatching=ie,exports.isAlreadyInstrumented=function(n){return!!n.includes("captureFunctionSpan(")||!!n.includes("@sailfish-ai/sf-veritas")||!(!n.includes("/* @sailfish-instrumented */")&&!n.includes("// @sailfish-instrumented"))},exports.isConfigLoaderInitialized=Y,exports.isSetupInterceptorsInitialized=function(){return M},exports.isWorkerPoolInitialized=se,exports.setupInterceptors=function(n){if(H)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!M){H=!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)}Y()||Q(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)"):se()||(ie(),e.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const t=new K;t.setServiceUUID(e.serviceUUID),h.initializeLogInterceptor(t),(function(r=[]){const i=new $e(r);new Ie().doSend(i.getExcludedDomains());const l=new _e,s=new ve;i.patchFetch(l,s),i.patchHttp(l,s)})(e.domainsToNotPropagateHeadersTo);const o=new me;o.setServiceUUID(e.serviceUUID),h.initializeExceptionInterceptor(o),ye(),new be().send(),M=!0,e.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{H=!1}}};
|