@sailfish-ai/sf-veritas 0.2.4 → 0.2.6

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 (44) hide show
  1. package/README.md +120 -0
  2. package/dist/funcSpanTransformer-TjdooSrw.cjs +1 -0
  3. package/dist/funcSpanTransformer-sqmZLAcs.js +750 -0
  4. package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
  5. package/dist/plugins/funcspanEsbuildPlugin.mjs +1 -1
  6. package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
  7. package/dist/plugins/funcspanRollupPlugin.mjs +1 -1
  8. package/dist/plugins/funcspanTscPlugin.cjs +1 -1
  9. package/dist/plugins/funcspanTscPlugin.mjs +1 -1
  10. package/dist/plugins/funcspanVitePlugin.cjs +1 -1
  11. package/dist/plugins/funcspanVitePlugin.mjs +1 -1
  12. package/dist/plugins/funcspanWebpackLoader.cjs +1 -1
  13. package/dist/plugins/funcspanWebpackLoader.mjs +65 -8
  14. package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
  15. package/dist/plugins/funcspanWebpackPlugin.mjs +24 -24
  16. package/dist/runtime/register.cjs +1 -0
  17. package/dist/runtime/register.mjs +27 -0
  18. package/dist/sf-veritas.cjs +16 -52
  19. package/dist/sf-veritas.mjs +573 -811
  20. package/dist/types/functionSpanTransmitter.d.ts +15 -1
  21. package/dist/types/index.d.ts +2 -0
  22. package/dist/types/patches/workerPool/argumentCapture.d.ts +47 -0
  23. package/dist/types/patches/workerPool/index.d.ts +19 -0
  24. package/dist/types/patches/workerPool/patchCrypto.d.ts +9 -0
  25. package/dist/types/patches/workerPool/patchDns.d.ts +10 -0
  26. package/dist/types/patches/workerPool/patchFs.d.ts +9 -0
  27. package/dist/types/patches/workerPool/patchZlib.d.ts +9 -0
  28. package/dist/types/patches/workerPool/workerPoolTypes.d.ts +70 -0
  29. package/dist/types/plugins/funcspanWebpackPlugin.d.ts +20 -0
  30. package/dist/types/plugins/workerPoolTransformer.d.ts +42 -0
  31. package/dist/types/requestUtils.d.ts +1 -0
  32. package/dist/types/runtime/register.d.ts +56 -0
  33. package/dist/types/worker-pool-capture.d.ts +9 -0
  34. package/dist/types/workerPoolConfig.d.ts +22 -0
  35. package/dist/types/workerPoolSpanCapture.d.ts +36 -0
  36. package/dist/worker-pool-capture.cjs +1 -0
  37. package/dist/worker-pool-capture.mjs +4 -0
  38. package/dist/workerPoolSpanCapture-BOnYC4s3.js +705 -0
  39. package/dist/workerPoolSpanCapture-CNEouInA.cjs +83 -0
  40. package/package.json +17 -1
  41. package/dist/funcSpanTransformer-CTddGtUV.cjs +0 -1
  42. package/dist/funcSpanTransformer-coYDqcrs.js +0 -136
  43. package/dist/source-map-Cr6YkjTd.js +0 -631
  44. package/dist/source-map-rHHEdpre.cjs +0 -1
@@ -1,4 +1,4 @@
1
- "use strict";var Ve=Object.defineProperty;var we=(o,e,t)=>e in o?Ve(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var C=(o,e,t)=>we(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("async_hooks"),re=require("fs"),Ze=require("./source-map-rHHEdpre.cjs"),He=require("worker_threads"),Re=require("path"),Ye=require("glob");function ve(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const O=ve(re),G=ve(Re),Z=[];for(let o=0;o<256;++o)Z.push((o+256).toString(16).slice(1));let P;const Ue=new Uint8Array(16),le={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function R(o,e,t){if(le.randomUUID&&!o)return le.randomUUID();const n=(o=o||{}).random??o.rng?.()??(function(){if(!P){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");P=crypto.getRandomValues.bind(crypto)}return P(Ue)})();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(i,s=0){return(Z[i[s+0]]+Z[i[s+1]]+Z[i[s+2]]+Z[i[s+3]]+"-"+Z[i[s+4]]+Z[i[s+5]]+"-"+Z[i[s+6]]+Z[i[s+7]]+"-"+Z[i[s+8]]+Z[i[s+9]]+"-"+Z[i[s+10]]+Z[i[s+11]]+Z[i[s+12]]+Z[i[s+13]]+Z[i[s+14]]+Z[i[s+15]]).toLowerCase()})(n)}class Ke{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=R(),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 Ge=Symbol.for("sailfish.sf_config");function x(){return globalThis[Ge]}function Te(o){const e=x();if(e)return{config:e};const t=new Ke(o);return(function(n){globalThis[Ge]=n})(t),t.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",t),{config:t}}function l(){const o=x();if(!o)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return o}const de=Symbol.for("sf.ctx.storeAls"),W=globalThis,M=W[de]??(W[de]=new se.AsyncLocalStorage),Ne=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],Ie=Symbol.for("sf.ctx.als"),K=W[Ie]??(W[Ie]=new se.AsyncLocalStorage),ue=Symbol.for("sf.ctx.sessionRegistry"),Y=W[ue]??(W[ue]=new Map),E={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(Ne),supportedDomains:new Set},V=class V{constructor(){}current(){return M.getStore()}ensureStore(){const e=this.current();if(e)return e;const t=new Map;return M.enterWith(t),t}runWith(e,t){const n=this.current()??new Map,i=new Map(n);for(const[s,g]of Object.entries(e))i.set(s,g);return M.run(i,t)}static getInstance(){return W[V.GLOBAL_MANAGER_SYMBOL]||(W[V.GLOBAL_MANAGER_SYMBOL]=new V),W[V.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return K.getStore()||E}setCurrentContext(e){const t=K.getStore()||E;K.enterWith({...t,...e})}ensureSession(e){let t=Y.get(e);return t||(t={...E},Y.set(e,t)),t}getContextFor(e){return Y.get(e)??E}updateContextFor(e,t){const n=this.ensureSession(e);Y.set(e,{...n,...t})}runWithSession(e,t){const n={...this.ensureSession(e)};return K.run(n,t)}deleteSession(e){Y.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?R():`nonsession-applogs-v3/${l().apiKey}/${R()}`),this.setTraceId(n),l().sfDebug&&console.log(" Created new trace ID:",n),n)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=R(),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})}};C(V,"GLOBAL_MANAGER_SYMBOL",Symbol.for("sf.ctx.manager"));let v=V;function $(){return v.getInstance().getCurrentFunctionSpanId()}class w{constructor(){C(this,"apiKey");C(this,"endpoint");C(this,"queryType","mutation");C(this,"operationName","");C(this,"serviceUUID",l().serviceUUID);C(this,"contextManager");this.apiKey=l().apiKey,this.endpoint=l().apiGraphqlEndpoint,this.contextManager=v.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const e=Date.now().toString(),t=this.contextManager.getOrSetSfTraceId(),n=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:t,timestampMs:e,parentSpanId:n}}getVariables(e={}){return{...this.getDefaultVariables(),...e}}setOperationName(e){this.operationName=e}setEndpoint(e){this.endpoint=e}setServiceUUID(e){this.serviceUUID=e}}const Je=fetch;async function F(o,e,t,n){try{const i=l();let s;try{s=JSON.stringify({query:t,variables:n,operationName:e})}catch{s=JSON.stringify({query:t,operationName:e})}Je(o,{method:"POST",headers:{"Content-Type":"application/json"},body:s}).then(async g=>{if(!g.ok)return void(i.sfDebug&&console.error(`GraphQL request failed with status ${g.status} for ${e}`));const r=await g.json();r.errors?.length?(function(a,c,d){const I=a&&typeof a=="object"&&!Array.isArray(a)?Object.keys(a)[0]:void 0;console.error(I==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${d.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(c)} for operation key ${I}`)})(r.data,r.errors,i):i.sfDebug&&(function(a,c,d){const I=a&&typeof a=="object"&&!Array.isArray(a)?Object.keys(a)[0]:void 0,h=a[I]||!1;I==="identifyServiceDetails"&&(d.setServiceIdentificationReceived(h),l().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${d.serviceUUID}; serviceIdentificationReceived=${I==="identifyServiceDetails"?h:"N/A"}`))})(r.data,0,i)}).catch(g=>{i.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${e} to ${o}:`,g),g.cause&&console.error("[RequestUtils] Error cause:",g.cause))})}catch(i){l().sfDebug&&console.error("Error sending data to GraphQL server:",i)}}class X extends w{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!l().serviceIdentificationReceived)try{this.send()}catch(t){l().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
1
+ "use strict";var ue=Object.defineProperty;var Ce=(o,e,n)=>e in o?ue(o,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[e]=n;var A=(o,e,n)=>Ce(o,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./workerPoolSpanCapture-CNEouInA.cjs"),X=require("fs"),D=require("./funcSpanTransformer-TjdooSrw.cjs"),N=require("worker_threads"),pe=require("node:module"),me=require("path"),he=require("glob");var k=typeof document<"u"?document.currentScript:null;function de(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const n in o)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(o,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:()=>o[n]})}}return e.default=o,Object.freeze(e)}const T=de(X),S=de(me);class V extends r.BaseTransmitter{constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!r.getConfig().serviceIdentificationReceived)try{this.send()}catch(n){r.getConfig().sfDebug&&console.error(" Error during service identification:",n)}}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:l().serviceIdentifier,serviceVersion:l().serviceVersion,library:l().packageLibraryType,version:l().version,serviceAdditionalMetadata:l().serviceAdditionalMetadata,gitSha:l().gitSha||""});F(this.endpoint,this.operationName,e,t)}}function Xe(o){try{return JSON.stringify(o),!0}catch{return!1}}class Ee extends w{constructor(){super();C(this,"serviceIdentifier",new X);this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,n,i,s){this.sendAppIdentifier(),this.send(t,n,i,s)}async send(t,n,i,s){if(!n&&!s)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let g=[];if(!s){const a=(function(c){const d={},I=[];if(c)for(const[h,p]of Object.entries(c))Xe(p)?d[h]=p:I.push(h);return{traitsJson:JSON.stringify(d),excludedFields:I}})(n);s=a.traitsJson,g=a.excludedFields}const r=this.getVariables({userId:t,traitsJson:s,excludedFields:g,override:i,library:l().packageLibraryType,version:l().version});F(this.endpoint,this.operationName,this.getQuery(),r)}getQuery(){return`
25
+ `,n=this.getVariables({serviceIdentifier:r.getConfig().serviceIdentifier,serviceVersion:r.getConfig().serviceVersion,library:r.getConfig().packageLibraryType,version:r.getConfig().version,serviceAdditionalMetadata:r.getConfig().serviceAdditionalMetadata,gitSha:r.getConfig().gitSha||""});r.nonBlockingPost(this.endpoint,this.operationName,e,n)}}function be(o){try{return JSON.stringify(o),!0}catch{return!1}}class Ae extends r.BaseTransmitter{constructor(){super();A(this,"serviceIdentifier",new V);this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(n,i,t,s){this.sendAppIdentifier(),this.send(n,i,t,s)}async send(n,i,t,s){if(!i&&!s)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let l=[];if(!s){const g=(function(c){const d={},I=[];if(c)for(const[p,C]of Object.entries(c))be(C)?d[p]=C:I.push(p);return{traitsJson:JSON.stringify(d),excludedFields:I}})(i);s=g.traitsJson,l=g.excludedFields}const a=this.getVariables({userId:n,traitsJson:s,excludedFields:l,override:t,library:r.getConfig().packageLibraryType,version:r.getConfig().version});r.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),a)}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 Ce{constructor(e){C(this,"metadataTransmitter");this.apiKey=e,this.metadataTransmitter=new Ee}identify(e,t,n,i=!1){t||n?this.addOrUpdateMetadata(e,t,n,i):this.addOrUpdateMetadata(e,{},void 0,i)}addOrUpdateMetadata(e,t={},n,i=!1){if(!t&&!n)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');l().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),l().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,n),this.metadataTransmitter.doSend(e,t,i,n)}}class ae extends w{constructor(){super();C(this,"serviceIdentifier",new X)}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){try{const n=Array.isArray(t)?t:[t,"default"],i=this.getVariables({contents:n[0],level:n[1]});F(this.endpoint,this.operationName,this.getQuery(),i)}catch(n){l().sfDebug&&console.error("🚨 Error in send():",n)}}getQuery(){return`
29
+ `}}class O{constructor(e){A(this,"metadataTransmitter");this.apiKey=e,this.metadataTransmitter=new Ae}identify(e,n,i,t=!1){n||i?this.addOrUpdateMetadata(e,n,i,t):this.addOrUpdateMetadata(e,{},void 0,t)}addOrUpdateMetadata(e,n={},i,t=!1){if(!n&&!i)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');r.getConfig().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),r.getConfig().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,n,i),this.metadataTransmitter.doSend(e,n,t,i)}}class P extends r.BaseTransmitter{constructor(){super();A(this,"serviceIdentifier",new V)}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(n){this.sendAppIdentifier(),this.send(n)}async send(n){try{const i=Array.isArray(n)?n:[n,"default"],t=this.getVariables({contents:i[0],level:i[1]});r.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),t)}catch(i){r.getConfig().sfDebug&&console.error("🚨 Error in send():",i)}}getQuery(){return`
30
30
  ${this.queryType} ${this.operationName}(
31
31
  $apiKey: String!,
32
32
  $serviceUuid: String!,
@@ -46,11 +46,11 @@
46
46
  parentSpanId: $parentSpanId
47
47
  )
48
48
  }
49
- `}}const N={};class T{constructor({file:e,line:t,function:n,code:i,locals:s={},offender:g=!1,column:r}){C(this,"file");C(this,"line");C(this,"function");C(this,"code");C(this,"locals");C(this,"offender");C(this,"column");this.file=e,this.line=t,this.function=n,this.code=i,this.locals=s,this.offender=g,this.column=r}toDict(){const e={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([t,n])=>[t,String(n)]))};return this.offender&&(e.offender=this.offender),this.column!==void 0&&(e.column=this.column),e}toJson(){return JSON.stringify(this.toDict())}}class z{static encode(e){return e instanceof T?e.toDict():Array.isArray(e)?e.map(t=>z.encode(t)):typeof e=="object"&&e!==null?JSON.stringify(e):e}static stringify(e){return JSON.stringify(z.encode(e),(t,n)=>n instanceof T?n.toDict():n)}}let B,U=0;function _e(o){l().sfDebug&&console.log("Initializing Exception Interceptor...");try{const r=(function(){if(B!==void 0)return B;const a=process.env||{},c=Ae(a.SF_IS_LOCAL);if(c!==void 0)return B=c;const d=(a.SF_ENV||a.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(h=>!!a[h]))return B=!1;const I=(N.hostname?.()||a.HOSTNAME||"").toLowerCase();return I==="localhost"||I.endsWith(".local")||I.includes("local")?B=!0:B=!1})();o?.setSupplementalFields?.({isFromLocalService:r}),(async function(a){if(he)return;he=!0;const c=process.env||{};if(Ae(c.SF_IS_LOCAL)===void 0)try{await(async function(d){const I=j("http://169.254.169.254/latest/meta-data/",{},d),h=j("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},d),p=j("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},d);return(await Promise.allSettled([I,h,p])).some(u=>u.status==="fulfilled"&&(u.value==="ok"||u.value==="http_error"))})(150)&&B&&(B=!1,a?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(o).catch(()=>{})}catch{}const e=new He.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB1bmRlZmluZWQ7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB1bmRlZmluZWQ7CgovKioKICogUHJvY2V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AgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiI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AgICAgICAgZmlyc3RGcmFtZUxpbmUuaW5jbHVkZXMoYCR7bW9kdWxlTmFtZX1gKSwKICAgICAgICApOwoKICAgICAgICBpZiAoIWlzRnJvbUFsbG93ZWROb2RlTW9kdWxlKSB7CiAgICAgICAgICAvLyBOb3QgZnJvbSBhbiBhbGxvd2VkIG5vZGUgbW9kdWxlID0+IHJldHVybiBlYXJseQogICAgICAgICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgICAgICAgIGNvbnNvbGUubG9nKAogICAgICAgICAgICAgICJbV29ya2VyXSBFcnJvciBhcHBlYXJzIHRvIGJlIHRyaWdnZXJlZCBmcm9tIG5vbi1hcHBsaWNhdGlvbiBzb3VyY2VzOyBpZ25vcmluZy4iLAogICAgICAgICAgICApOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KICAgICAgICAvLyBPdGhlcndpc2UsIGl0J3MgZnJvbSBhbiBhbGxvd2VkIG5vZGUgbW9kdWxlLCBzbyBjb250aW51ZQogICAgICB9IGVsc2UgewogICAgICAgIC8vIElmIHRoZSBsaXN0IGlzIGVtcHR5LCBwcmVzZXJ2ZSBleGlzdGluZyBiZWhhdmlvciBhbmQgaWdub3JlIG5vbi1hcHBsaWNhdGlvbiBlcnJvcnMKICAgICAgICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgICAgICAgIGNvbnNvbGUubG9nKAogICAgICAgICAgICAiW1dvcmtlcl0gRXJyb3IgYXBwZWFycyB0byBiZSB0cmlnZ2VyZWQgZnJvbSBub24tYXBwbGljYXRpb24gc291cmNlczsgaWdub3JpbmcuIiwKICAgICAgICAgICk7CiAgICAgICAgfQogICAgICAgIHJldHVybjsKICAgICAgfQogICAgfQoKICAgIC8vIElmIHdlIHJlYWNoIHRoaXMgcG9pbnQsIHRoZSBlcnJvciBpcyBlaXRoZXIgZnJvbSBhcHAgY29kZSwgb3IgZnJvbSBhIG5vZGUgbW9kdWxlIGFsbG93ZWQgYnkgd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NmRGVidWcpIHsKICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlcjoiLCBlcnJvcik7CiAgfQp9KTsKCi8vIEtlZXAgdGhlIHdvcmtlciBhbGl2ZQpzZXRJbnRlcnZhbCgoKSA9PiB7fSwgMTAwMDApOwo="),{workerData:{captureAllExceptions:!0}});let t=null;const n=new WeakMap;e.on("message",r=>{if(typeof r=="string"&&l().sfDebug&&console.log(`[Worker] ${r}`),r.readyToGetParameters&&e.postMessage({sfDebug:l().sfDebug,stackDepthLocals:l().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:l().nodeModulesToCollectLocalVariablesOn}),r.type==="exception"){const{frames:a}=r,c=t;if(!c)return;const d=n.get(c),I=(function(p){return p?p.split(`
50
- `).slice(1).map(u=>{const A=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(u)||/at (.+):(\d+):(\d+)/.exec(u);if(A){const[,m,y,b,f]=A;return new T({function:m||"<anonymous>",locals:{},file:y||"<unknown>",line:parseInt(b,10)||0,code:"<not captured>",column:parseInt(f)||0})}return new T({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(c.stack),h=(function(p,u){const A=[];let m=-1,y=-1;for(let b=0;b<p.length;b++){const f=$e(p[b].file);if(y=b,f!=="<unknown>"){for(let S=0;S<u.length;S++){const k=u[S];if(Be(k,f)||typeof k.file=="string"&&k.file.includes(f)){m=S,U=0,l().sfDebug&&console.log(`✅ Matched Frame Found: ${f} @ Debugger Frame ${S}`);break}}if(m!==-1)break}}if(m===-1)return U===10?(U=0,p):(++U,l().sfDebug&&console.log(`"❌ No matching frame found. Checking once again, Attempt N ${U}"`),[]);l().sfDebug&&console.log(`🔄 Merging from matched index ${m} onward...`);for(let b=0;b<u.length;b++){const f=p[y+b],S=u[m+b];A.push(new T({function:S?.function||f?.function||"<anonymous>",locals:S?.locals||f?.locals||{},file:f?.file||S?.file||"<unknown>",line:S?.line||f?.line||0,code:S?.code||f?.code||"<not captured>"}))}return A})(I,a||[]);if(h.length!==0){t=null;const p=l().stackDepthCodeTraceDepth,u=p===-1?h:h.slice(0,p+1),A=Math.min(u.length,I.length);for(let f=0;f<A;f++)(async()=>{const S=De(u[f].file,I[f].line,I[f].column);S&&(S.content!=null&&(u[f].code=S.content),S.file!=null&&(u[f].file=S.file))})();o.setOperationName("CollectExceptions");const m=c.message?`${c.name}: ${c.message}`:c.name;l().sfDebug&&console.log("error message is : ",m);const y=v.getInstance(),b=n.get(c);b?(y.setTraceIdFor(b,b),y.runWithSession(b,()=>{y.setTraceId(b),o.doSend(m,u)})):o.doSend(m,u),d?v.getInstance().runWithSession(d,()=>{o.doSend(m,u)}):o.doSend(m,u)}}}),e.on("error",r=>{console.error("[Worker Error]",r)}),e.on("exit",r=>{console.error(`[Worker] Exited with code ${r}`)}),e.unref();const i=Error,s=new Set;function g(...r){const a=Reflect.construct(i,r);Reflect.setPrototypeOf(a,g.prototype);try{const d=v.getInstance().getTraceId();n.set(a,d)}catch{}i.captureStackTrace&&i.captureStackTrace(a,g);const c=`${a.message}:${a.stack?.split(`
51
- `)[1]?.trim()}`;if(!s.has(c)){s.add(c),t=a;const d=v.getInstance().getTraceId();n.set(a,d),e.postMessage({type:"processException",error:a.message})}return a}g.prototype=Object.create(i.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(g,i),globalThis.Error=g}function pe(o){return o=(o=(o=o.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function De(o,e,t){const n=(function(s){s.startsWith("at ")&&(s=s.slice(3).trim());const g=s.match(/^(.*?)(:\d+)+(\.map)?$/);return g?g[1]:s})(o);if(!n||n==="<unknown>")return null;const i=n+".map";try{const s=re.readFileSync(i,"utf-8");if(s){const g=JSON.parse(s);let r=new Ze.sourceMapExports.SourceMapConsumer(g).originalPositionFor({line:e,column:t});if(n&&r.source){const a=pe(n),c=g.sources.findIndex(d=>pe(d)===a);if(c===-1)l().sfDebug&&console.log(`Source file "${n}" not found in the source map.`);else{const d=g.sourcesContent[c],I=g.names.join(",");if(d)return{content:d.split(`
52
- `).slice(r.line-1,r.line+20).join(`
53
- `),name:I,file:r.source};l().sfDebug&&console.log(`No source content available for file "${n}".`)}}return{content:g.sourcesContent[0],name:g.names[0],file:g.file}}}catch(s){l().sfDebug&&console.log(`Cant read/parse "${i}: Error - ".`,s)}return null}function $e(o){return o?.split("/").pop()||"<unknown>"}function Be(o,e){if(!o||typeof o!="object")return!1;for(const t of Object.values(o))if(typeof t=="string"&&t.includes(e)||typeof t=="object"&&Be(t,e))return!0;return!1}let he=!1;function Ae(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 j(o,e,t){return new Promise(n=>{try{const i=new URL(o),s=(i.protocol,N).request({method:"GET",hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+(i.search||""),headers:e},g=>{g.resume(),g.statusCode&&g.statusCode>=200&&g.statusCode<400?n("ok"):n("http_error")});s.on("error",()=>n("error")),s.setTimeout(t,()=>{s.destroy(),n("timeout")}),s.end()}catch{n("error")}})}class Le extends w{constructor(){super();C(this,"serviceIdentifier",new X);C(this,"supplementalFields",{});this.setOperationName("CollectExceptions")}setSupplementalFields(t){this.supplementalFields={...this.supplementalFields,...t}}normalizedSupplementalForGraphQL(){const{isFromLocalService:t}=this.supplementalFields,n={};return t!==void 0&&(n.isFromLocalService=t),n}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,n){this.sendAppIdentifier(),this.send(t,n)}async send(t,n){l().sfDebug&&console.log(" SENDING EXCEPTION...");const i=JSON.stringify(z.encode(n)),s=this.normalizedSupplementalForGraphQL(),g=this.getVariables({exceptionMessage:t,traceJson:i,reentrancyGuardPreactive:!1,library:l().packageLibraryType,version:l().version,...s});F(this.endpoint,this.operationName,this.getQuery(),g)}getQuery(){return`
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,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB1bmRlZmluZWQ7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB1bmRlZmluZWQ7CgovKioKICogUHJvY2Vzc2VzIGNhbGwgZnJhbWVzIGZyb20gYW4gZXhjZXB0aW9uIGFuZCBwb3N0cyB0aGVtIHZpYSB0aGUgV29ya2Vy4oCZcyBwYXJlbnRQb3J0LgogKgogKiBAcGFyYW0gc2Vzc2lvbiAtIFRoZSBEZXZUb29scyBzZXNzaW9uIG9yIHNpbWlsYXIgb2JqZWN0IHlvdSB1c2UgdG8gcXVlcnkgZm9yIHNjcmlwdCBzb3VyY2VzLgogKiBAcGFyYW0gY2FsbEZyYW1lcyAtIEFuIGFycmF5IG9mIGNhbGwgZnJhbWUgb2JqZWN0cy4KICogQHBhcmFtIGRlc2NyaXB0aW9uTGluZXMgLSBBbiBhcnJheSBvZiBsaW5lcyBmcm9tIHRoZSBlcnJvcuKAmXMgZGVzY3JpcHRpb24sIGVhY2ggdHlwaWNhbGx5IGJlZ2lubmluZyB3aXRoICJhdCAiLgogKiBAcmV0dXJucyB7UHJvbWlzZTx2b2lkPn0KICovCmV4cG9ydCBhc3luYy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jcmlwdGlvbkxpbmVzW2luZGV4XSkgewogICAgICAgICAgZmlsZSA9IGRlc2NyaXB0aW9uTGluZXNbaW5kZXhdLnRyaW0oKTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgZmlsZSA9ICI8dW5rbm93bj4iOwogICAgICAgIH0KCiAgICAgICAgLy8gSWYgd2UgaGF2ZSBhIHZhbGlkIGxvY2F0aW9uIGFuZCBzY3JpcHRJZCwgZmV0Y2ggdGhlIGNvZGUgbGluZQogICAgICAgIGlmIChsb2NhdGlvbiAmJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHsgc2NyaXB0U291cmNlIH0gPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgIkRlYnVnZ2VyLmdldFNjcmlwdFNvdXJjZSIsCiAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IiwKICAgICAgICB9OwogICAgICB9CiAgICB9KSwKICApOwogIC8vIFBvc3QgZXhjZXB0aW9uIGRhdGEKICBwYXJlbnRQb3J0Py5wb3N0TWVzc2FnZSh7IHR5cGU6ICJleGNlcHRpb24iLCBmcmFtZXMgfSk7Cn0KCi8qKgogKiBIYW5kbGVzIHRoZSAicGF1c2VkIiBzdGF0ZSBvZiB0aGUgZGVidWdnZXIgYW5kIHByb2Nlc3NlcyBleGNlcHRpb25zIG9yIHByb21pc2UgcmVqZWN0aW9ucy4KICogQHBhcmFtIHtTZXNzaW9ufSBzZXNzaW9uIC0g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gICAgICAgICBjb25zdCBpZCA9IHByb3AudmFsdWUub2JqZWN0SWQ7CiAgICAgICAgICBhd2FpdCB1bnJvbGxPYmplY3Qoc2Vzc2lvbiwgaWQsIHByb3AubmFtZSwgdmFyaWFibGVzKTsKICAgICAgICB9IGVsc2UgaWYgKHByb3A/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`
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 me="getting request source code";var L=(o=>(o.UNKNOWN="unknown",o.ANONYMOUS="anonymous",o.NOT_CAPTURED="not captured",o))(L||{});const Q="http:",q="https:";function ce(){return{capture_arguments:H(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:H(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:H(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:H(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:H(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:H(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}}function ze(){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}}function ie(o){try{const e=o.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 "${o}":`,e),null}}function H(o,e){if(!o)return e;const t=o.toLowerCase();return t==="true"||t==="1"||t==="yes"}const ge=new se.AsyncLocalStorage;function We(o){ge.enterWith(o)}function oe(){return ge.getStore()}function Fe(){ge.enterWith(void 0)}function _(...o){const e={};for(const t of o)for(const n in t)t[n]!==void 0&&(e[n]=t[n]);return e}function ee(o,e){try{const t=JSON.stringify(o).length/1048576;return t<=e?o:{_truncated:!0,_originalSizeMB:t.toFixed(2),_limitMB:e,_preview:JSON.stringify(o).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof o}}}let be=!1;function xe(){const o=l().sfDebug;if(be)return void(o&&console.log("[patchNodeHttpInbound] Already installed, skipping."));let e;be=!0;try{e=require("node:http"),o&&console.log("[patchNodeHttpInbound] node:http required successfully.")}catch(i){return void console.error("Failed to require node:http:",i)}if(!e?.Server?.prototype)return void(o&&console.log("[patchNodeHttpInbound] http.Server.prototype not found."));const t=e.Server.prototype,n=t.emit;n&&!t.__sf_inbound_patched__?(Object.defineProperty(t,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),o&&console.log("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(i,...s){if(i!=="request")return o&&console.log(`[patchNodeHttpInbound] Passing through event: ${i}`),n.call(this,i,...s);const g=s[0],r=s[1],a=(function(p){const u={};if(!p)return u;for(const[A,m]of Object.entries(p))m!=null&&(Array.isArray(m)?u[A.toLowerCase()]=m.join(", "):u[A.toLowerCase()]=String(m));return u})(g?.headers),c=a["x-sf3-rid"],d=a["x-sf3-functionspancaptureoverride"];o&&(console.log("[patchNodeHttpInbound] Intercepted request event."),console.log("[patchNodeHttpInbound] Inbound headers:",a),console.log("[patchNodeHttpInbound] Trace header:",c),console.log("[patchNodeHttpInbound] FuncSpan override header:",d));const I=v.getInstance();I.setTraceId(c);const h=I.getTraceId();return o&&console.log("[patchNodeHttpInbound] Context traceId set:",h),I.runWith({inboundHeaders:a,...c?{traceId:c}:{}},()=>{c&&I.setTraceId(c),d&&(We(d),o&&console.log("[patchNodeHttpInbound] FuncSpan override set:",d)),o&&console.log("[patchNodeHttpInbound] Running request handler in context.");const p=()=>{o&&console.log("[patchNodeHttpInbound] Response finished/closed for traceId:",I.getTraceId()),d&&(Fe(),o&&console.log("[patchNodeHttpInbound] FuncSpan override cleared"))};return r.on("finish",p),r.on("close",p),n.call(this,i,g,r)})}):o&&console.log("[patchNodeHttpInbound] Already patched, skipping.")}class ke extends ae{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
81
+ `}}const q="getting request source code";var Y=(o=>(o.UNKNOWN="unknown",o.ANONYMOUS="anonymous",o.NOT_CAPTURED="not captured",o))(Y||{});const _="http:",z="https:",Ge=pe.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:k&&k.tagName.toUpperCase()==="SCRIPT"&&k.src||new URL("sf-veritas.cjs",document.baseURI).href);let ee=!1;function Be(){const o=r.getConfig().sfDebug;if(ee)return void(o&&console.log("[patchNodeHttpInbound] Already installed, skipping."));let e;ee=!0;try{e=Ge("node:http"),o&&console.log("[patchNodeHttpInbound] node:http required successfully.")}catch(t){return void console.error("Failed to require node:http:",t)}if(!e?.Server?.prototype)return void(o&&console.log("[patchNodeHttpInbound] http.Server.prototype not found."));const n=e.Server.prototype,i=n.emit;i&&!n.__sf_inbound_patched__?(Object.defineProperty(n,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),o&&console.log("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),n.emit=function(t,...s){if(t!=="request")return o&&console.log(`[patchNodeHttpInbound] Passing through event: ${t}`),i.call(this,t,...s);const l=s[0],a=s[1],g=(function(C){const u={};if(!C)return u;for(const[m,h]of Object.entries(C))h!=null&&(Array.isArray(h)?u[m.toLowerCase()]=h.join(", "):u[m.toLowerCase()]=String(h));return u})(l?.headers),c=g["x-sf3-rid"],d=g["x-sf3-functionspancaptureoverride"];o&&(console.log("[patchNodeHttpInbound] Intercepted request event."),console.log("[patchNodeHttpInbound] Inbound headers:",g),console.log("[patchNodeHttpInbound] Trace header:",c),console.log("[patchNodeHttpInbound] FuncSpan override header:",d));const I=r.ContextManager.getInstance();I.setTraceId(c);const p=I.getTraceId();return o&&console.log("[patchNodeHttpInbound] Context traceId set:",p),I.runWith({inboundHeaders:g,...c?{traceId:c}:{}},()=>{c&&I.setTraceId(c),d&&(r.setFuncspanOverride(d),o&&console.log("[patchNodeHttpInbound] FuncSpan override set:",d)),o&&console.log("[patchNodeHttpInbound] Running request handler in context.");const C=()=>{o&&console.log("[patchNodeHttpInbound] Response finished/closed for traceId:",I.getTraceId()),d&&(r.clearFuncspanOverride(),o&&console.log("[patchNodeHttpInbound] FuncSpan override cleared"))};return a.on("finish",C),a.on("close",C),i.call(this,t,l,a)})}):o&&console.log("[patchNodeHttpInbound] Already patched, skipping.")}class ve extends P{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const n=`
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
- `,n={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};F(this.endpoint,this.operationName,t,n)}}class Oe extends w{constructor(){super();C(this,"serviceIdentifier",new X);this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}async send(t){const{name:n,column:i,line:s,entrypoint:g,retryWithoutTraceId:r}=t,a=this.getVariables({name:n,column:i,line:s,entrypoint:g,retryWithoutTraceId:r});F(this.endpoint,this.operationName,this.getQuery(),a)}getQuery(){return`
93
+ `,i={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};r.nonBlockingPost(this.endpoint,this.operationName,n,i)}}class We extends r.BaseTransmitter{constructor(){super();A(this,"serviceIdentifier",new V);this.setOperationName("CollectNetworkHops")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(n){this.sendAppIdentifier(),this.send(n)}async send(n){const{name:i,column:t,line:s,entrypoint:l,retryWithoutTraceId:a}=n,g=this.getVariables({name:i,column:t,line:s,entrypoint:l,retryWithoutTraceId:a});r.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),g)}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 Pe extends w{constructor(){super();C(this,"serviceIdentifier",new X);this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t){this.sendAppIdentifier(),this.send(t)}getQuery(){return`
117
+ `}}class Ne extends r.BaseTransmitter{constructor(){super();A(this,"serviceIdentifier",new V);this.setOperationName("CollectNetworkRequest")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(n){this.sendAppIdentifier(),this.send(n)}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(t){const n={data:{...t}};await F(this.endpoint,this.operationName,this.getQuery(),n)}}const te=[400,403];class Me{constructor(e=[]){C(this,"HEADER_TRACING","X-Sf3-Rid");C(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");C(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");C(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");C(this,"contextManager");this.contextManager=v.getInstance(),e?.forEach(t=>{typeof t=="string"&&t.trim()&&this.contextManager.getExcludedDomains().add(t)}),l().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let n;if(e instanceof Headers)n=e.get(t)??void 0;else{const s=t.toLowerCase();for(const[g,r]of Object.entries(e))if(g.toLowerCase()===s){n=r;break}}if(!n)return{};const i=n.split("/").filter(Boolean);return i.length<3?{}:{sessionId:i[0],pageVisitId:i[1],requestId:i[i.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,n,i,s]=t;return{filePath:n,line:parseInt(i,10),column:parseInt(s,10)}}async getOriginalPosition(e,t,n){let i={source:e,line:t,column:n,name:null};const s=e+".map";try{const g=JSON.parse(re.readFileSync(s,"utf-8"));let r=(await new Ze.sourceMapExports.SourceMapConsumer(g)).originalPositionFor({line:t,column:n});r.source&&(i=r)}catch(g){l().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,g)}return{originalPos:i}}captureFirstUserLines(e,t=10,n=!1){const i=l().sfDebug?10:t,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,i);const g=new Error(me);me in Error&&Error.captureStackTrace(g,this.captureFirstUserLines);const r=g.stack||"";Error.stackTraceLimit=s;const a=r.split(`
125
- `).slice(1),c=[];for(const d of a)if(!(d.includes("node:internal")||d.includes("internal/modules")||d.includes("internal/process")||d.includes("node_modules")||d.includes(".next/server/chunks")||d.includes("RequestInterceptor")||d.includes("contextManager")||d.includes("setupConfig"))&&(c.push(d.trim()),c.length>=t))break;for(const d of c){const I=this.parseStackFrame(d);I?(async()=>{const{originalPos:h}=await this.getOriginalPosition(I.filePath,I.line,I.column);if(h){l().sfDebug&&console.log("[RequestInterceptor] First user code line:",h);const p={line:h.line?.toString()||L.UNKNOWN,column:h.column?.toString()||L.NOT_CAPTURED,name:h.name||L.NOT_CAPTURED,entrypoint:h.source,retryWithoutTraceId:n};e.doSend(p)}})():l().sfDebug&&console.error("Could not parse stack line:",d)}}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!Ne.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const n=new URL(t).hostname,i=this.shouldPropagateHeaders(n);return i?this.addTracingHeader(e,t):l().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${n}`),i}addTracingHeader(e,t){const n=oe();if(n){const r=ie(n);if(r&&r.sample_rate===0)return void(l().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const i=this.contextManager.getOrSetSfTraceId(),s=this.contextManager.getOrSetPageVisitUUID(),g=R();e.set(this.HEADER_TRACING,`${i}/${s}/${g}`),l().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const n=globalThis.fetch;typeof n=="function"?globalThis.fetch=async(i,s)=>{const g=new Headers(s?.headers);if(g.get(this.HEADER_LOG_GUARD)==="true"||g.get(this.HEADER_PRINT_GUARD)==="true"||g.get(this.HEADER_EXCEPTION_GUARD)==="true")return n(i,s);this.captureFirstUserLines(e);const r=Date.now();let a;typeof i=="string"||i instanceof URL?a=i.toString():i instanceof Request?(a=i.url,i.headers.forEach((u,A)=>{g.set(A,u)})):l().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),l().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",a);const c=new URL(a).hostname,d=new Headers(g),I=this.addTracingHeaders(g,a),h={...s,headers:g};let p;try{let u=!1;this.addTracingHeaders(d,a),p=await n(a,h),I&&te.includes(p.status)?(p=await n(a,{...s,headers:d}),u=!0,this.captureFirstUserLines(e,10,u)):this.contextManager.addSupportedDomains(c);const A=Date.now();l().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${a}, Status: ${p.status}, Duration: ${A-r}ms`);const{sessionId:m,pageVisitId:y,requestId:b}=this.extractIdsFromTraceHeader(g);return t.doSend({apiKey:l().apiKey,requestId:b,pageVisitId:y,recordingSessionId:m,serviceUuid:l().serviceUUID,timestampStart:r.toString(),timestampEnd:A.toString(),responseCode:p.status,success:!0,error:null,url:a,method:h.method||"GET",retryWithoutTraceId:u,parentSpanId:$()}),p}catch(u){const A=Date.now();l().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${a}, Error: ${u}, Duration: ${A-r}ms`)}}:l().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(l().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!N||typeof N.request!="function")return void(l().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const n=N.request.bind(N),i=N.request.bind(N);N.request=function(s,g){let r;try{if(typeof s=="string"){const c=new URL(s);r={protocol:c.protocol||Q,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?r={protocol:s.protocol||Q,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(r={...s},r.protocol||(r.protocol=Q));if(r.headers){const c=`${r.protocol}//${r.hostname}`;this.addTracingHeaders(r.headers,c),this.captureFirstUserLines(e)}else l().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(c){throw l().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",c),c}let a=!1;return n(r,c=>{const d=`${r.protocol}//${r.hostname}`;if(r.headers&&this.shouldPropagateHeaders(new URL(d).hostname)&&te.includes(c.statusCode||0)){r.hostname;const u={...r,headers:{...r.headers}};delete u.headers[this.HEADER_TRACING],n(u,g),a=!0,this.captureFirstUserLines(e,10,a)}const{sessionId:I,pageVisitId:h,requestId:p}=this.extractIdsFromTraceHeader(r.headers);t.doSend({apiKey:l().apiKey,requestId:p,pageVisitId:h,recordingSessionId:I,serviceUuid:l().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:d,method:r.method||"GET",retryWithoutTraceId:a,parentSpanId:$()}),g?.(c)})},N.request=function(s,g){let r;try{if(typeof s=="string"){const c=new URL(s);r={protocol:c.protocol||q,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?r={protocol:s.protocol||q,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(r={...s},r.protocol||(r.protocol=q));if(r.headers){const c=`${r.protocol}//${r.hostname}`;this.addTracingHeaders(r.headers,c)}else l().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(c){throw l().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",c),c}let a=!1;return i(r,c=>{const d=`${r.protocol}//${r.hostname}`;if(r.headers&&this.shouldPropagateHeaders(new URL(d).hostname)&&te.includes(c.statusCode||0)){const u={...r,headers:{...r.headers}};delete u.headers[this.HEADER_TRACING],i(u,g),a=!0,this.captureFirstUserLines(e,10,a)}const{sessionId:I,pageVisitId:h,requestId:p}=this.extractIdsFromTraceHeader(r.headers);t.doSend({apiKey:l().apiKey,requestId:p,pageVisitId:h,recordingSessionId:I,serviceUuid:l().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:d,method:r.method||"GET",retryWithoutTraceId:a,parentSpanId:$()}),g?.(c)})},l().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e(),console.log(`[RequestInterceptor] Patched ${t}`)}catch(n){console.warn(`[RequestInterceptor] Could not patch ${t}: ${n.message}`)}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class je extends ae{constructor(){super(),this.setOperationName("UpdateServiceDetails")}async doSend(){this.sendAppIdentifier(),this.send()}async send(){const e=`
124
+ `}async send(n){const i={data:{...n}};await r.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),i)}}const E=[400,403];class Fe{constructor(e=[]){A(this,"HEADER_TRACING","X-Sf3-Rid");A(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");A(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");A(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");A(this,"contextManager");this.contextManager=r.ContextManager.getInstance(),e?.forEach(n=>{typeof n=="string"&&n.trim()&&this.contextManager.getExcludedDomains().add(n)}),r.getConfig().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,n=this.HEADER_TRACING){let i;if(e instanceof Headers)i=e.get(n)??void 0;else{const s=n.toLowerCase();for(const[l,a]of Object.entries(e))if(l.toLowerCase()===s){i=a;break}}if(!i)return{};const t=i.split("/").filter(Boolean);return t.length<3?{}:{sessionId:t[0],pageVisitId:t[1],requestId:t[t.length-1]}}parseStackFrame(e){const n=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!n)return null;const[,i,t,s]=n;return{filePath:i,line:parseInt(t,10),column:parseInt(s,10)}}async getOriginalPosition(e,n,i){let t={source:e,line:n,column:i,name:null};const s=e+".map";try{const l=JSON.parse(X.readFileSync(s,"utf-8"));let a=(await new D.sourceMapExports.SourceMapConsumer(l)).originalPositionFor({line:n,column:i});a.source&&(t=a)}catch(l){r.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,l)}return{originalPos:t}}captureFirstUserLines(e,n=10,i=!1){const t=r.getConfig().sfDebug?10:n,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,t);const l=new Error(q);q in Error&&Error.captureStackTrace(l,this.captureFirstUserLines);const a=l.stack||"";Error.stackTraceLimit=s;const g=a.split(`
125
+ `).slice(1),c=[];for(const d of g)if(!(d.includes("node:internal")||d.includes("internal/modules")||d.includes("internal/process")||d.includes("node_modules")||d.includes(".next/server/chunks")||d.includes("RequestInterceptor")||d.includes("contextManager")||d.includes("setupConfig"))&&(c.push(d.trim()),c.length>=n))break;for(const d of c){const I=this.parseStackFrame(d);I?(async()=>{const{originalPos:p}=await this.getOriginalPosition(I.filePath,I.line,I.column);if(p){r.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",p);const C={line:p.line?.toString()||Y.UNKNOWN,column:p.column?.toString()||Y.NOT_CAPTURED,name:p.name||Y.NOT_CAPTURED,entrypoint:p.source,retryWithoutTraceId:i};e.doSend(C)}})():r.getConfig().sfDebug&&console.error("Could not parse stack line:",d)}}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!r.DEFAULT_DOMAINS_TO_EXCLUDE.some(n=>new RegExp(`^${n.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,n){const i=new URL(n).hostname,t=this.shouldPropagateHeaders(i);return t?this.addTracingHeader(e,n):r.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),t}addTracingHeader(e,n){const i=r.getFuncspanOverride();if(i){const a=r.parseHeaderOverride(i);if(a&&a.sample_rate===0)return void(r.getConfig().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${n}`))}const t=this.contextManager.getOrSetSfTraceId(),s=this.contextManager.getOrSetPageVisitUUID(),l=r.v4();e.set(this.HEADER_TRACING,`${t}/${s}/${l}`),r.getConfig().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${n}`)}patchFetch(e,n){const i=globalThis.fetch;typeof i=="function"?globalThis.fetch=async(t,s)=>{const l=new Headers(s?.headers);if(l.get(this.HEADER_LOG_GUARD)==="true"||l.get(this.HEADER_PRINT_GUARD)==="true"||l.get(this.HEADER_EXCEPTION_GUARD)==="true")return i(t,s);this.captureFirstUserLines(e);const a=Date.now();let g;typeof t=="string"||t instanceof URL?g=t.toString():t instanceof Request?(g=t.url,t.headers.forEach((u,m)=>{l.set(m,u)})):r.getConfig().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),r.getConfig().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",g);const c=new URL(g).hostname,d=new Headers(l),I=this.addTracingHeaders(l,g),p={...s,headers:l};let C;try{let u=!1;this.addTracingHeaders(d,g),C=await i(g,p),I&&E.includes(C.status)?(C=await i(g,{...s,headers:d}),u=!0,this.captureFirstUserLines(e,10,u)):this.contextManager.addSupportedDomains(c);const m=Date.now();r.getConfig().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${g}, Status: ${C.status}, Duration: ${m-a}ms`);const{sessionId:h,pageVisitId:Z,requestId:b}=this.extractIdsFromTraceHeader(l);return n.doSend({apiKey:r.getConfig().apiKey,requestId:b,pageVisitId:Z,recordingSessionId:h,serviceUuid:r.getConfig().serviceUUID,timestampStart:a.toString(),timestampEnd:m.toString(),responseCode:C.status,success:!0,error:null,url:g,method:p.method||"GET",retryWithoutTraceId:u,parentSpanId:r.getCurrentFunctionSpanId()}),C}catch(u){const m=Date.now();r.getConfig().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${g}, Error: ${u}, Duration: ${m-a}ms`)}}:r.getConfig().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,n){if(r.getConfig().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!G||typeof G.request!="function")return void(r.getConfig().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const i=G.request.bind(G),t=G.request.bind(G);G.request=function(s,l){let a;try{if(typeof s=="string"){const c=new URL(s);a={protocol:c.protocol||_,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?a={protocol:s.protocol||_,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(a={...s},a.protocol||(a.protocol=_));if(a.headers){const c=`${a.protocol}//${a.hostname}`;this.addTracingHeaders(a.headers,c),this.captureFirstUserLines(e)}else r.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(c){throw r.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",c),c}let g=!1;return i(a,c=>{const d=`${a.protocol}//${a.hostname}`;if(a.headers&&this.shouldPropagateHeaders(new URL(d).hostname)&&E.includes(c.statusCode||0)){a.hostname;const u={...a,headers:{...a.headers}};delete u.headers[this.HEADER_TRACING],i(u,l),g=!0,this.captureFirstUserLines(e,10,g)}const{sessionId:I,pageVisitId:p,requestId:C}=this.extractIdsFromTraceHeader(a.headers);n.doSend({apiKey:r.getConfig().apiKey,requestId:C,pageVisitId:p,recordingSessionId:I,serviceUuid:r.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:d,method:a.method||"GET",retryWithoutTraceId:g,parentSpanId:r.getCurrentFunctionSpanId()}),l?.(c)})},G.request=function(s,l){let a;try{if(typeof s=="string"){const c=new URL(s);a={protocol:c.protocol||z,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?a={protocol:s.protocol||z,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(a={...s},a.protocol||(a.protocol=z));if(a.headers){const c=`${a.protocol}//${a.hostname}`;this.addTracingHeaders(a.headers,c)}else r.getConfig().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(c){throw r.getConfig().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",c),c}let g=!1;return t(a,c=>{const d=`${a.protocol}//${a.hostname}`;if(a.headers&&this.shouldPropagateHeaders(new URL(d).hostname)&&E.includes(c.statusCode||0)){const u={...a,headers:{...a.headers}};delete u.headers[this.HEADER_TRACING],t(u,l),g=!0,this.captureFirstUserLines(e,10,g)}const{sessionId:I,pageVisitId:p,requestId:C}=this.extractIdsFromTraceHeader(a.headers);n.doSend({apiKey:r.getConfig().apiKey,requestId:C,pageVisitId:p,recordingSessionId:I,serviceUuid:r.getConfig().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:c.statusCode||0,success:!!c.statusCode&&c.statusCode<400,error:null,url:d,method:a.method||"GET",retryWithoutTraceId:g,parentSpanId:r.getCurrentFunctionSpanId()}),l?.(c)})},r.getConfig().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,n){try{require.resolve(n),e(),console.log(`[RequestInterceptor] Patched ${n}`)}catch(i){console.warn(`[RequestInterceptor] Could not patch ${n}: ${i.message}`)}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class we extends P{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,42 +142,6 @@
142
142
  gitSha: $gitSha,
143
143
  )
144
144
  }
145
- `,t=this.getVariables({serviceIdentifier:l().serviceIdentifier,serviceVersion:l().serviceVersion,serviceAdditionalMetadata:l().serviceAdditionalMetadata,gitSha:l().gitSha||""});F(this.endpoint,this.operationName,e,t)}}class Qe{constructor(e=[process.cwd()],t=!1){C(this,"rootPaths");C(this,"fileConfigs",new Map);C(this,"functionConfigs",new Map);C(this,"directoryConfigs",new Map);C(this,"hasSailfishFiles",!1);C(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)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 n=this.hasSailfishFiles?ce():{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},i=this._getDirectoryConfig(e),s=G.normalize(e),g=this.fileConfigs.get(s)||{};let r={};if(t){const a=this.functionConfigs.get(s);a&&(r=a.get(t)||{})}return _(n,i,g,r)}async _walkDirectory(e,t){try{const n=O.readdirSync(e,{withFileTypes:!0});for(const i of n){const s=G.join(e,i.name);i.isFile()&&i.name===".sailfish"?t.push(s):i.name==="node_modules"||i.isDirectory()&&i.name.startsWith(".")&&i.name!==".sailfish"||i.isDirectory()&&await this._walkDirectory(s,t)}}catch(n){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,n)}}async _loadConfigFile(e){try{const t=O.readFileSync(e,"utf-8"),n=G.dirname(e);let i=null;try{i=JSON.parse(t)}catch{try{i=require("js-yaml").load(t)}catch(s){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,s))}}if(!i)return;i.default&&this.directoryConfigs.set(n,i.default),i.files&&await this._expandFileGlobs(n,i.files,i.default||{}),i.functions&&this._storeFunctionConfigs(n,i.functions,i.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${n}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!i.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(i.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(i.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,n){for(const[i,s]of Object.entries(t))try{const g=G.join(e,i),r=await Ye.glob(g,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${i}' matched ${r.length} files`);for(const a of r){const c=G.normalize(a),d=_(n,s);this.fileConfigs.set(c,d),this.debug&&r.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${a}`)}}catch(g){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${i}':`,g)}}_storeFunctionConfigs(e,t,n){for(const[i,s]of Object.entries(t)){const g=i.split("::");if(g.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${i}' (expected format: 'file.ts::functionName')`);continue}const[r,a]=g,c=G.normalize(G.join(e,r));this.functionConfigs.has(c)||this.functionConfigs.set(c,new Map);const d=this.functionConfigs.get(c),I=_(n,s);d.set(a,I),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${c}::${a}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=G.dirname(G.normalize(e));const n=[];for(;t&&t!==G.dirname(t);){const i=this.directoryConfigs.get(t);i&&n.unshift(i),t=G.dirname(t)}return n.reduce((i,s)=>_(i,s),{})}}let J=null;async function fe(o,e){J=new Qe(o,e),await J.loadAllConfigs()}function ye(o,e){return J?J.getConfig(o,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),ce())}function Se(){return J!==null}class qe extends w{constructor(){super(),this.operationName="CollectFunctionSpans"}send(e){const t=l().sfDebug;t&&console.log(`[FunctionSpanTransmitter] Preparing to send ${e.length} function span(s)`);for(const n of e)try{let i;if(n.result!==void 0&&n.result!==null){const g=typeof n.result;i=JSON.stringify({type:g,has_value:!0,value:n.result})}else i=n.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:l().version,spanId:n.spanId,parentSpanId:n.parentSpanId,filePath:n.filePath,lineNumber:n.metadata.line,columnNumber:n.metadata.column,functionName:n.functionName,arguments:JSON.stringify(n.args||{}),returnValue:i,startTimeNs:(1e6*Date.now()-1e6*n.duration).toString(),durationNs:(1e6*n.duration).toString()});t&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(s,null,2))),F(this.endpoint,this.operationName,this.getQuery(),s),t&&console.log(`[FunctionSpanTransmitter] Queued function span for ${n.functionName}`)}catch(i){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${n.functionName}:`,i)}}getQuery(){return`
146
- ${this.queryType} ${this.operationName}(
147
- $apiKey: String!,
148
- $serviceUuid: String!,
149
- $sessionId: String!,
150
- $timestampMs: String!,
151
- $parentSpanId: String,
152
- $library: String!,
153
- $version: String!,
154
- $spanId: String!,
155
- $filePath: String!,
156
- $lineNumber: Int!,
157
- $columnNumber: Int!,
158
- $functionName: String!,
159
- $arguments: String!,
160
- $returnValue: String,
161
- $startTimeNs: String!,
162
- $durationNs: String!
163
- ) {
164
- ${this.queryName}(
165
- apiKey: $apiKey,
166
- serviceUuid: $serviceUuid,
167
- sessionId: $sessionId,
168
- timestampMs: $timestampMs,
169
- parentSpanId: $parentSpanId,
170
- library: $library,
171
- version: $version,
172
- spanId: $spanId,
173
- filePath: $filePath,
174
- lineNumber: $lineNumber,
175
- columnNumber: $columnNumber,
176
- functionName: $functionName,
177
- arguments: $arguments,
178
- returnValue: $returnValue,
179
- startTimeNs: $startTimeNs,
180
- durationNs: $durationNs
181
- )
182
- }
183
- `}}let ne=null;function D(o){const e=x(),t=e?.sfDebug||!1;t&&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 n={functionName:o.functionName,filePath:o.filePath,metadata:o.metadata,args:o.args,result:o.result,error:o.error,duration:o.duration,async:o.async,spanId:o.spanId,parentSpanId:o.parentSpanId};t&&console.log("[FuncSpan] Sending function span to transmitter:",n);try{(ne||(ne=new qe),ne).send([n]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(i){console.error("[FuncSpan] Error sending function span:",i)}}exports.ContextManager=v,exports.addOrUpdateMetadata=function(o,e={},t,n=!1){const i=l();new Ce(i.apiKey).addOrUpdateMetadata(o,e,t,n)},exports.captureFunctionSpan=function(o,e,t,n){const i=function(...s){const g=x(),r=g?.sfDebug||!1;r&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const a=(function(u,A){const m=oe();if(m){const y=ie(m);if(y)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${u}::${A}`),y}return ye(u,A)})(t,e);if(r&&console.log(`[FuncSpan] Config for ${t}::${e}:`,a),a.enable_sampling&&a.sample_rate<1&&Math.random()>a.sample_rate)return r&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),o.apply(this,s);if(a.sample_rate===0)return r&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),o.apply(this,s);r&&console.log(`[FuncSpan] Capturing function span for ${e}`);const c=v.getInstance(),d=c.getCurrentFunctionSpanId(),I=R();c.setCurrentFunctionSpanId(I);const h=Date.now();let p=null;a.capture_arguments&&(p={},n.paramNames.forEach((u,A)=>{A<s.length&&(p[u]=s[A])}),p&&a.arg_limit_mb>0&&(p=ee(p,a.arg_limit_mb)));try{const u=o.apply(this,s);if(u&&typeof u.then=="function")return u.then(y=>{const b=Date.now();let f=null;return a.capture_return_value&&a.return_limit_mb>0&&(f=ee(y,a.return_limit_mb)),D({functionName:e,filePath:t,metadata:n,args:p,result:f,error:null,duration:b-h,async:!0,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),y},y=>{const b=Date.now();throw D({functionName:e,filePath:t,metadata:n,args:p,result:null,error:y?.message||String(y),duration:b-h,async:!0,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),y});const A=Date.now();let m=null;return a.capture_return_value&&a.return_limit_mb>0&&(m=ee(u,a.return_limit_mb)),D({functionName:e,filePath:t,metadata:n,args:p,result:m,error:null,duration:A-h,async:!1,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),u}catch(u){const A=Date.now();throw D({functionName:e,filePath:t,metadata:n,args:p,result:null,error:u?.message||String(u),duration:A-h,async:!1,spanId:I,parentSpanId:d}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),u}};Object.defineProperty(i,"name",{value:e,writable:!1});for(const s in o)o.hasOwnProperty(s)&&(i[s]=o[s]);return i},exports.clearFuncspanOverride=Fe,exports.getCurrentFunctionSpanId=$,exports.getDefaultConfig=ze,exports.getEnvConfig=ce,exports.getFuncspanOverride=oe,exports.getGlobalConfig=ye,exports.identify=function(o,e,t,n=!1){const i=l();new Ce(i.apiKey).identify(o,e,t,n)},exports.initializeConfigLoader=fe,exports.isConfigLoaderInitialized=Se,exports.parseHeaderOverride=ie,exports.runWithContext=function(o){const e={...v.getInstance().getCurrentContext()};K.run(e,()=>{o()})},exports.setFuncspanOverride=We,exports.setupInterceptors=function(o){if(!o||!o.apiKey){const i=`The required API Key is not provided: ${JSON.stringify(o)}`;console.error(i)}const{config:e}=Te(o);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const i=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(i),new Error(i)}Se()||fe(void 0,e.sfDebug).catch(i=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",i)});const t=new ae;t.setServiceUUID(e.serviceUUID),(function(i){function s(I,h){i.setOperationName("CollectLogs"),i.doSend([h,I])}const g=console.log.bind(console),r=console.error.bind(console),a=console.warn.bind(console),c=console.info.bind(console),d=console.debug.bind(console);console.log=(...I)=>{s("INFO",I.join(" ")),g(...I)},console.error=(...I)=>{s("ERROR",I.join(" ")),r(...I)},console.warn=(...I)=>{s("WARN",I.join(" ")),a(...I)},console.info=(...I)=>{s("INFO",I.join(" ")),c(...I)},l().logLevel==="DEBUG"&&(console.debug=(...I)=>{s("DEBUG",I.join(" ")),d(...I)})})(t),(function(i=[]){const s=new Me(i);new ke().doSend(s.getExcludedDomains());const g=new Oe,r=new Pe;s.patchFetch(g,r),s.patchHttp(g,r)})(e.domainsToNotPropagateHeadersTo);const n=new Le;n.setServiceUUID(e.serviceUUID),_e(n),xe(),new je().send()};
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:`${o.functionName} (${o.filePath}:${o.metadata.line}:${o.metadata.column})`,duration:`${o.duration.toFixed(2)}ms`,arguments:o.args,result:o.error?`Error: ${o.error}`:o.result,spanId:o.spanId,parentSpanId:o.parentSpanId||"none"});const t=process.env.SF_FUNCSPAN_JSONL_FILE;if(t)try{const s=t==="true"||t==="1"?"funcspans.jsonl":t,l=Date.now(),a=process.hrtime.bigint(),g=BigInt(o.startTimeNs),c=Number(a-g)/1e6,d=new Date(l-c).toISOString(),I=JSON.stringify({timestamp:d,functionName:o.functionName,filePath:o.filePath,line:o.metadata.line,column:o.metadata.column,duration:o.duration,durationNs:o.durationNs,startTimeNs:o.startTimeNs,arguments:o.args,returnValue:o.error?{error:String(o.error)}:o.result,spanId:o.spanId,parentSpanId:o.parentSpanId,async:o.async,pid:o.pid,threadId:o.threadId})+`
147
+ `;X.appendFileSync(s,I,"utf-8")}catch(s){console.error("[FuncSpan] Error writing to JSONL file:",s)}if(n&&console.log("[FuncSpan] Sending function span to transmitter:",i),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{($||($=new r.FunctionSpanTransmitter),$).send([i]),n&&console.log("[FuncSpan] Function span sent successfully")}catch(s){n&&console.error("[FuncSpan] Error sending function span:",s)}}exports.ContextManager=r.ContextManager,exports.clearFuncspanOverride=r.clearFuncspanOverride,exports.getCurrentFunctionSpanId=r.getCurrentFunctionSpanId,exports.getDefaultConfig=r.getDefaultConfig,exports.getEnvConfig=r.getEnvConfig,exports.getFuncspanOverride=r.getFuncspanOverride,exports.parseHeaderOverride=r.parseHeaderOverride,exports.runWithContext=r.runWithContext,exports.setFuncspanOverride=r.setFuncspanOverride,exports.transformFunctionSpans=D.transformFunctionSpans,exports.addOrUpdateMetadata=function(o,e={},n,i=!1){const t=r.getConfig();new O(t.apiKey).addOrUpdateMetadata(o,e,n,i)},exports.captureFunctionSpan=function(o,e,n,i){const t=function(...s){const l=r.getGlobalConfigUnsafe(),a=l?.sfDebug||!1;a&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${n}::${e}`);const g=(function(m,h){const Z=r.getFuncspanOverride();if(Z){const b=r.parseHeaderOverride(Z);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${m}::${h}`),b}try{return te(m,h)}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}}})(n,e);if(a&&console.log(`[FuncSpan] Config for ${n}::${e}:`,g),g.enable_sampling&&g.sample_rate<1&&Math.random()>g.sample_rate)return a&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),o.apply(this,s);if(g.sample_rate===0)return a&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),o.apply(this,s);a&&console.log(`[FuncSpan] Capturing function span for ${e}`);const c=r.ContextManager.getInstance(),d=c.getCurrentFunctionSpanId(),I=r.v4();c.setCurrentFunctionSpanId(I);const p=process.hrtime.bigint(),C=Date.now();let u=null;g.capture_arguments&&(u={},i.paramNames.forEach((m,h)=>{h<s.length&&(u[m]=s[h])}),u&&g.arg_limit_mb>0&&(u=r.truncateToLimit(u,g.arg_limit_mb)));try{const m=o.apply(this,s);if(m&&typeof m.then=="function")return d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),m.then(f=>{const v=process.hrtime.bigint(),J=Date.now(),K=Number(v-p);let x=null;return g.capture_return_value&&g.return_limit_mb>0&&(x=r.truncateToLimit(f,g.return_limit_mb)),H({functionName:e,filePath:n,metadata:i,args:u,result:x,error:null,duration:J-C,durationNs:K,startTimeNs:p.toString(),async:!0,spanId:I,parentSpanId:d,pid:process.pid,threadId:N.threadId}),f},f=>{const v=process.hrtime.bigint(),J=Date.now(),K=Number(v-p);throw H({functionName:e,filePath:n,metadata:i,args:u,result:null,error:f?.message||String(f),duration:J-C,durationNs:K,startTimeNs:p.toString(),async:!0,spanId:I,parentSpanId:d,pid:process.pid,threadId:N.threadId}),f});const h=process.hrtime.bigint(),Z=Date.now(),b=Number(h-p);let y=null;return g.capture_return_value&&g.return_limit_mb>0&&(y=r.truncateToLimit(m,g.return_limit_mb)),H({functionName:e,filePath:n,metadata:i,args:u,result:y,error:null,duration:Z-C,durationNs:b,startTimeNs:p.toString(),async:!1,spanId:I,parentSpanId:d,pid:process.pid,threadId:N.threadId}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),m}catch(m){const h=process.hrtime.bigint(),Z=Date.now(),b=Number(h-p);throw H({functionName:e,filePath:n,metadata:i,args:u,result:null,error:m?.message||String(m),duration:Z-C,durationNs:b,startTimeNs:p.toString(),async:!1,spanId:I,parentSpanId:d,pid:process.pid,threadId:N.threadId}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),m}};Object.defineProperty(t,"name",{value:e,writable:!1});for(const s in o)o.hasOwnProperty(s)&&(t[s]=o[s]);return t},exports.getGlobalConfig=te,exports.identify=function(o,e,n,i=!1){const t=r.getConfig();new O(t.apiKey).identify(o,e,n,i)},exports.initializeConfigLoader=ne,exports.initializeWorkerPoolPatching=ge,exports.isConfigLoaderInitialized=oe,exports.isWorkerPoolInitialized=le,exports.setupInterceptors=function(o){if(!o||!o.apiKey){const t=`The required API Key is not provided: ${JSON.stringify(o)}`;console.error(t)}const{config:e}=r.getOrCreateConfig(o);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const t=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(t),new Error(t)}oe()||ne(void 0,e.sfDebug).catch(t=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",t)}),le()||(ge(),e.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const n=new P;n.setServiceUUID(e.serviceUUID),(function(t){function s(I,p){t.setOperationName("CollectLogs"),t.doSend([p,I])}const l=console.log.bind(console),a=console.error.bind(console),g=console.warn.bind(console),c=console.info.bind(console),d=console.debug.bind(console);console.log=(...I)=>{s("INFO",I.join(" ")),l(...I)},console.error=(...I)=>{s("ERROR",I.join(" ")),a(...I)},console.warn=(...I)=>{s("WARN",I.join(" ")),g(...I)},console.info=(...I)=>{s("INFO",I.join(" ")),c(...I)},r.getConfig().logLevel==="DEBUG"&&(console.debug=(...I)=>{s("DEBUG",I.join(" ")),d(...I)})})(n),(function(t=[]){const s=new Fe(t);new ve().doSend(s.getExcludedDomains());const l=new We,a=new Ne;s.patchFetch(l,a),s.patchHttp(l,a)})(e.domainsToNotPropagateHeadersTo);const i=new Se;i.setServiceUUID(e.serviceUUID),fe(i),Be(),new we().send()};