@sailfish-ai/sf-veritas 0.2.5 → 0.2.7

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.
@@ -1,4 +1,4 @@
1
- "use strict";var et=Object.defineProperty;var tt=(n,e,t)=>e in n?et(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var C=(n,e,t)=>tt(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const te=require("async_hooks"),L=require("fs"),fe=require("./funcSpanTransformer-TjdooSrw.cjs"),w=require("worker_threads"),nt=require("node:module"),rt=require("path"),ot=require("glob");var oe=typeof document<"u"?document.currentScript:null;function Xe(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const se=Xe(L),G=Xe(rt),N=[];for(let n=0;n<256;++n)N.push((n+256).toString(16).slice(1));let ie;const st=new Uint8Array(16),ve={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function V(n,e,t){if(ve.randomUUID&&!n)return ve.randomUUID();const s=(n=n||{}).random??n.rng?.()??(function(){if(!ie){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ie=crypto.getRandomValues.bind(crypto)}return ie(st)})();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=15&s[6]|64,s[8]=63&s[8]|128,(function(r,a=0){return(N[r[a+0]]+N[r[a+1]]+N[r[a+2]]+N[r[a+3]]+"-"+N[r[a+4]]+N[r[a+5]]+"-"+N[r[a+6]]+N[r[a+7]]+"-"+N[r[a+8]]+N[r[a+9]]+"-"+N[r[a+10]]+N[r[a+11]]+N[r[a+12]]+N[r[a+13]]+N[r[a+14]]+N[r[a+15]]).toLowerCase()})(s)}class it{constructor(e){C(this,"apiKey");C(this,"apiGraphqlEndpoint");C(this,"sfDebug");C(this,"serviceIdentifier");C(this,"serviceVersion");C(this,"serviceUUID");C(this,"serviceAdditionalMetadata");C(this,"profilingModeEnabled");C(this,"profilingMaxDepth");C(this,"profilingMaxVariableSizeKb");C(this,"domainsToNotPropagateHeadersTo");C(this,"nodeModulesToCollectLocalVariablesOn");C(this,"printConfigurationStatuses");C(this,"logLevel");C(this,"stackDepthLocals");C(this,"stackDepthCodeTraceDepth");C(this,"packageLibraryType");C(this,"version");C(this,"gitSha");C(this,"_serviceIdentificationReceived",!1);this.apiKey=e.apiKey,this.apiGraphqlEndpoint=e?.apiGraphqlEndpoint||process.env.SAILFISH_GRAPHQL_ENDPOINT||"https://api-service.sailfishqa.com/graphql/",this.sfDebug=e?.debug===!0||process.env.SF_DEBUG==="true",this.serviceIdentifier=e?.serviceIdentifier||process.env.SERVICE_IDENTIFIER,this.serviceUUID=V(),this.serviceVersion=e?.serviceVersion||process.env.SERVICE_VERSION,this.gitSha=e?.gitSha||process.env.GIT_SHA||process.env.VERCEL_GIT_COMMIT_SHA,this.serviceAdditionalMetadata=e?.serviceAdditionalMetadata||{},this.profilingModeEnabled=e?.profilingModeEnabled??!1,this.profilingMaxDepth=e?.profilingMaxDepth??5,this.profilingMaxVariableSizeKb=e?.profilingMaxVariableSizeKb??25,this.domainsToNotPropagateHeadersTo=e?.domainsToNotPropagateHeadersTo||[],this.nodeModulesToCollectLocalVariablesOn=e?.nodeModulesToCollectLocalVariablesOn||["_all_"],this.printConfigurationStatuses=process.env.PRINT_CONFIGURATION_STATUSES||"true",this.logLevel=process.env.LOG_LEVEL||"INFO",this.stackDepthLocals=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS,10):5,isNaN(this.stackDepthLocals)&&(this.stackDepthLocals=-1),this.stackDepthCodeTraceDepth=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH,10):-1,isNaN(this.stackDepthCodeTraceDepth)&&(this.stackDepthCodeTraceDepth=-1),this.packageLibraryType="JS/TS BACKEND",this.version=this.getPackageVersion()}getPackageVersion(){return"0.1.15"}get serviceIdentificationReceived(){return this._serviceIdentificationReceived}setServiceIdentificationReceived(e){this._serviceIdentificationReceived=e}}const Pe=Symbol.for("sailfish.sf_config");function H(){return globalThis[Pe]}function at(n){const e=H();if(e)return{config:e};const t=new it(n);return(function(s){globalThis[Pe]=s})(t),t.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",t),{config:t}}function d(){const n=H();if(!n)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return n}const Ge=Symbol.for("sf.ctx.storeAls"),_=globalThis,ae=_[Ge]??(_[Ge]=new te.AsyncLocalStorage),ze=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],Ze=Symbol.for("sf.ctx.als"),k=_[Ze]??(_[Ze]=new te.AsyncLocalStorage),Be=Symbol.for("sf.ctx.sessionRegistry"),E=_[Be]??(_[Be]=new Map),P={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(ze),supportedDomains:new Set},T=class T{constructor(){}current(){return ae.getStore()}ensureStore(){const e=this.current();if(e)return e;const t=new Map;return ae.enterWith(t),t}runWith(e,t){const s=this.current()??new Map,r=new Map(s);for(const[a,o]of Object.entries(e))r.set(a,o);return ae.run(r,t)}static getInstance(){return _[T.GLOBAL_MANAGER_SYMBOL]||(_[T.GLOBAL_MANAGER_SYMBOL]=new T),_[T.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return k.getStore()||P}setCurrentContext(e){const t=k.getStore()||P;k.enterWith({...t,...e})}ensureSession(e){let t=E.get(e);return t||(t={...P},E.set(e,t)),t}getContextFor(e){return E.get(e)??P}updateContextFor(e,t){const s=this.ensureSession(e);E.set(e,{...s,...t})}runWithSession(e,t){const s={...this.ensureSession(e)};return k.run(s,t)}deleteSession(e){E.delete(e)}getTraceId(){return this.getCurrentContext().traceId}getPageVisitUUID(){return this.getCurrentContext().pageVisitUUID}setTraceId(e){this.setCurrentContext({traceId:e})}setPageVisitUUID(e){this.setCurrentContext({pageVisitUUID:e})}getCurrentFunctionSpanId(){return this.getCurrentContext().currentFunctionSpanId}setCurrentFunctionSpanId(e){this.setCurrentContext({currentFunctionSpanId:e})}clearCurrentFunctionSpanId(){this.setCurrentContext({currentFunctionSpanId:void 0})}getOrSetSfTraceId(e,t=!1){let s=this.getTraceId();return s||(s=e||(t?V():`nonsession-applogs-v3/${d().apiKey}/${V()}`),this.setTraceId(s),d().sfDebug&&console.log(" Created new trace ID:",s),s)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=V(),this.setPageVisitUUID(e),d().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(T,"GLOBAL_MANAGER_SYMBOL",Symbol.for("sf.ctx.manager"));let v=T;function j(){return v.getInstance().getCurrentFunctionSpanId()}class ${constructor(){C(this,"apiKey");C(this,"endpoint");C(this,"queryType","mutation");C(this,"operationName","");C(this,"serviceUUID",d().serviceUUID);C(this,"contextManager");this.apiKey=d().apiKey,this.endpoint=d().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(),s=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:t,timestampMs:e,parentSpanId:s}}getVariables(e={}){return{...this.getDefaultVariables(),...e}}setOperationName(e){this.operationName=e}setEndpoint(e){this.endpoint=e}setServiceUUID(e){this.serviceUUID=e}}const ct=fetch;let z=!1;async function W(n,e,t,s){try{const r=d();let a;try{a=JSON.stringify({query:t,variables:s,operationName:e})}catch{a=JSON.stringify({query:t,operationName:e})}z=!0,ct(n,{method:"POST",headers:{"Content-Type":"application/json"},body:a}).then(async o=>{if(z=!1,!o.ok)return void(r.sfDebug&&console.error(`GraphQL request failed with status ${o.status} for ${e}`));const i=await o.json();i.errors?.length?(function(c,l,g){const u=c&&typeof c=="object"&&!Array.isArray(c)?Object.keys(c)[0]:void 0;console.error(u==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${g.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(l)} for operation key ${u}`)})(i.data,i.errors,r):r.sfDebug&&(function(c,l,g){const u=c&&typeof c=="object"&&!Array.isArray(c)?Object.keys(c)[0]:void 0,I=c[u]||!1;u==="identifyServiceDetails"&&(g.setServiceIdentificationReceived(I),d().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${g.serviceUUID}; serviceIdentificationReceived=${u==="identifyServiceDetails"?I:"N/A"}`))})(i.data,0,r)}).catch(o=>{z=!1,r.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${e} to ${n}:`,o),o.cause&&console.error("[RequestUtils] Error cause:",o.cause))})}catch(r){z=!1,d().sfDebug&&console.error("Error sending data to GraphQL server:",r)}}class X extends ${constructor(){super(),this.setOperationName("IdentifyServiceDetails")}async doSend(e){if(!d().serviceIdentificationReceived)try{this.send()}catch(t){d().sfDebug&&console.error(" Error during service identification:",t)}}async send(){const e=`
1
+ "use strict";var me=Object.defineProperty;var he=(t,e,n)=>e in t?me(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var f=(t,e,n)=>he(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./workerPoolSpanCapture-DEwlTq0a.cjs"),X=require("fs"),O=require("./funcSpanTransformer-BpWuHXKT.cjs"),N=require("worker_threads"),be=require("node:module"),fe=require("path"),Ae=require("glob");var _=typeof document<"u"?document.currentScript:null;function Ce(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const k=Ce(X),S=Ce(fe);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:d().serviceIdentifier,serviceVersion:d().serviceVersion,library:d().packageLibraryType,version:d().version,serviceAdditionalMetadata:d().serviceAdditionalMetadata,gitSha:d().gitSha||""});W(this.endpoint,this.operationName,e,t)}}function lt(n){try{return JSON.stringify(n),!0}catch{return!1}}class gt extends ${constructor(){super();C(this,"serviceIdentifier",new X);this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,s,r,a){this.sendAppIdentifier(),this.send(t,s,r,a)}async send(t,s,r,a){if(!s&&!a)throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');let o=[];if(!a){const c=(function(l){const g={},u=[];if(l)for(const[I,m]of Object.entries(l))lt(m)?g[I]=m:u.push(I);return{traitsJson:JSON.stringify(g),excludedFields:u}})(s);a=c.traitsJson,o=c.excludedFields}const i=this.getVariables({userId:t,traitsJson:a,excludedFields:o,override:r,library:d().packageLibraryType,version:d().version});W(this.endpoint,this.operationName,this.getQuery(),i)}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 ye(t){try{return JSON.stringify(t),!0}catch{return!1}}class Ze extends r.BaseTransmitter{constructor(){super();f(this,"serviceIdentifier",new V);this.setOperationName("CollectMetadata")}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(n,i,o,s){this.sendAppIdentifier(),this.send(n,i,o,s)}async send(n,i,o,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[C,p]of Object.entries(c))ye(p)?d[C]=p:I.push(C);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:o,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 We{constructor(e){C(this,"metadataTransmitter");this.apiKey=e,this.metadataTransmitter=new gt}identify(e,t,s,r=!1){t||s?this.addOrUpdateMetadata(e,t,s,r):this.addOrUpdateMetadata(e,{},void 0,r)}addOrUpdateMetadata(e,t={},s,r=!1){if(!t&&!s)throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');d().sfDebug&&console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"),d().sfDebug&&console.log(" addOrUpdateMetadata...SENDING DATA...",e,t,s),this.metadataTransmitter.doSend(e,t,r,s)}}class be extends ${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 s=Array.isArray(t)?t:[t,"default"],r=this.getVariables({contents:s[0],level:s[1]});W(this.endpoint,this.operationName,this.getQuery(),r)}catch(s){d().sfDebug&&console.error("🚨 Error in send():",s)}}getQuery(){return`
29
+ `}}class M{constructor(e){f(this,"metadataTransmitter");this.apiKey=e,this.metadataTransmitter=new Ze}identify(e,n,i,o=!1){n||i?this.addOrUpdateMetadata(e,n,i,o):this.addOrUpdateMetadata(e,{},void 0,o)}addOrUpdateMetadata(e,n={},i,o=!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,o,i)}}class x extends r.BaseTransmitter{constructor(){super();f(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"],o=this.getVariables({contents:i[0],level:i[1]});r.nonBlockingPost(this.endpoint,this.operationName,this.getQuery(),o)}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 B={};class Y{constructor({file:e,line:t,function:s,code:r,locals:a={},offender:o=!1,column:i}){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=s,this.code=r,this.locals=a,this.offender=o,this.column=i}toDict(){const e={file:this.file,line:this.line,function:this.function,code:this.code,locals:Object.fromEntries(Object.entries(this.locals).map(([t,s])=>[t,String(s)]))};return this.offender&&(e.offender=this.offender),this.column!==void 0&&(e.column=this.column),e}toJson(){return JSON.stringify(this.toDict())}}class ee{static encode(e){return e instanceof Y?e.toDict():Array.isArray(e)?e.map(t=>ee.encode(t)):typeof e=="object"&&e!==null?JSON.stringify(e):e}static stringify(e){return JSON.stringify(ee.encode(e),(t,s)=>s instanceof Y?s.toDict():s)}}let F,K=0;function dt(n){d().sfDebug&&console.log("Initializing Exception Interceptor...");try{const i=(function(){if(F!==void 0)return F;const c=process.env||{},l=we(c.SF_IS_LOCAL);if(l!==void 0)return F=l;const g=(c.SF_ENV||c.NODE_ENV||"").toLowerCase();if(["local","dev","development"].includes(g))return F=!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(I=>!!c[I]))return F=!1;const u=(B.hostname?.()||c.HOSTNAME||"").toLowerCase();return u==="localhost"||u.endsWith(".local")||u.includes("local")?F=!0:F=!1})();n?.setSupplementalFields?.({isFromLocalService:i}),(async function(c){if(_e)return;_e=!0;const l=process.env||{};if(we(l.SF_IS_LOCAL)===void 0)try{await(async function(g){const u=ce("http://169.254.169.254/latest/meta-data/",{},g),I=ce("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},g),m=ce("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},g);return(await Promise.allSettled([u,I,m])).some(p=>p.status==="fulfilled"&&(p.value==="ok"||p.value==="http_error"))})(150)&&F&&(F=!1,c?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(n).catch(()=>{})}catch{}const e=new w.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7CmltcG9ydCB7IHBhcmVudFBvcnQsIHdvcmtlckRhdGEgfSBmcm9tICJ3b3JrZXJfdGhyZWFkcyI7CgpnbG9iYWwuc2ZEZWJ1ZyA9IHVuZGVmaW5lZDsKZ2xvYmFsLnN0YWNrRGVwdGhMb2NhbHMgPSB1bmRlZmluZWQ7Cmdsb2JhbC5ub2RlTW9kdWxlc1RvQ29sbGVjdExvY2FsVmFyaWFibGVzT24gPSB1bmRlZmluZWQ7CgovKioKICogUHJvY2Vzc2VzIGNhbGwgZnJhbWVzIGZyb20gYW4gZXhjZXB0aW9uIGFuZCBwb3N0cyB0aGVtIHZpYSB0aGUgV29ya2Vy4oCZcyBwYXJlbnRQb3J0LgogKgogKiBAcGFyYW0gc2Vzc2lvbiAtIFRoZSBEZXZUb29scyBzZXNzaW9uIG9yIHNpbWlsYXIgb2JqZWN0IHlvdSB1c2UgdG8gcXVlcnkgZm9yIHNjcmlwdCBzb3VyY2VzLgogKiBAcGFyYW0gY2FsbEZyYW1lcyAtIEFuIGFycmF5I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IGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgICAgICAgIGxvY2FscywKICAgICAgICAgIGZpbGUsCiAgICAgICAgICBsaW5lOiBsb2NhdGlvbj8ubGluZU51bWJlciB8fCAwLAogICAgICAgICAgY29kZSwKICAgICAgICB9OwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgY29uc29sZS5lcnJvcigiW1dvcmtlcl0gRXJyb3IgcHJvY2Vzc2luZyBjYWxsIGZyYW1lOiIsIGVycm9yKTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiAiPGVycm9yPiIsCiAgICAgICAgICBsb2NhbHM6IHt9LAogICAgICAgICAgZmlsZTogIjx1bmtub3duPiIsCiAgICAgICAgICBsaW5lOiAwLAogICAgICAgICAgY29kZTogIjxub3QgY2FwdHVyZWQ+IiwKICAgICAgICB9OwogICAgICB9CiAgICB9KSwKICApOwogIC8vIFBvc3QgZXhjZXB0aW9uIGRhdGEKICBwYXJlbn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Uub2JqZWN0SWQ7CiAgICAgICAgICBhd2FpdCB1bnJvbGxBcnJheShzZXNzaW9uLCBpZCwgcHJvcC5uYW1lLCB2YXJpYWJsZXMpOwogICAgICAgIH0gZWxzZSBpZiAoCiAgICAgICAgICBwcm9wPy52YWx1ZT8ub2JqZWN0SWQgJiYKICAgICAgICAgIHByb3A/LnZhbHVlPy5jbGFzc05hbWUgPT09ICJPYmplY3QiCiAgICAgICAgKSB7CiAgICAgICAgICBjb25zdCBpZCA9IHByb3AudmFsdWUub2JqZWN0SWQ7CiAgICAgICAgICBhd2FpdCB1bnJvbGxPYmplY3Qoc2Vzc2lvbiwgaWQsIHByb3AubmFtZSwgdmFyaWFibGVzKTsKICAgICAgICB9IGVsc2UgaWYgKHByb3A/LnZhbHVlKSB7CiAgICAgICAgICB1bnJvbGxPdGhlcihwcm9wLCB2YXJpYWJsZXMpOwogICAgICAgIH0KICAgICAgfQogICAgICByZXR1cm4gdmFyaWFibGVzOwogICAgfQogIH0gY2F0Y2ggKGVycikgewogICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBsb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+IHsKICBpZiAoZ2xvYmFsLnNmRGVidWcpIHsKICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBzdGFydCBkZWJ1Z2dlcjoiLCBlcnJvcik7CiAgfQp9KTsKCi8vIEtlZXAgdGhlIHdvcmtlciBhbGl2ZQpzZXRJbnRlcnZhbCgoKSA9PiB7fSwgMTAwMDApOwo="),{workerData:{captureAllExceptions:!0}});let t=null;const s=new WeakMap;e.on("message",i=>{if(typeof i=="string"&&d().sfDebug&&console.log(`[Worker] ${i}`),i.readyToGetParameters&&e.postMessage({sfDebug:d().sfDebug,stackDepthLocals:d().stackDepthLocals,nodeModulesToCollectLocalVariablesOn:d().nodeModulesToCollectLocalVariablesOn}),i.type==="exception"){const{frames:c}=i,l=t;if(!l)return;const g=s.get(l),u=(function(m){return m?m.split(`
50
- `).slice(1).map(p=>{const h=/at (.+?) \((.+):(\d+):(\d+)\)/.exec(p)||/at (.+):(\d+):(\d+)/.exec(p);if(h){const[,f,S,b,y]=h;return new Y({function:f||"<anonymous>",locals:{},file:S||"<unknown>",line:parseInt(b,10)||0,code:"<not captured>",column:parseInt(y)||0})}return new Y({function:"<unknown>",locals:{},file:"<unknown>",line:0,code:"<not captured>",column:0})}):[]})(l.stack),I=(function(m,p){const h=[];let f=-1,S=-1;for(let b=0;b<m.length;b++){const y=pt(m[b].file);if(S=b,y!=="<unknown>"){for(let A=0;A<p.length;A++){const Z=p[A];if(Oe(Z,y)||typeof Z.file=="string"&&Z.file.includes(y)){f=A,K=0,d().sfDebug&&console.log(`✅ Matched Frame Found: ${y} @ Debugger Frame ${A}`);break}}if(f!==-1)break}}if(f===-1)return K===10?(K=0,m):(++K,d().sfDebug&&console.log(`"❌ No matching frame found. Checking once again, Attempt N ${K}"`),[]);d().sfDebug&&console.log(`🔄 Merging from matched index ${f} onward...`);for(let b=0;b<p.length;b++){const y=m[S+b],A=p[f+b];h.push(new Y({function:A?.function||y?.function||"<anonymous>",locals:A?.locals||y?.locals||{},file:y?.file||A?.file||"<unknown>",line:A?.line||y?.line||0,code:A?.code||y?.code||"<not captured>"}))}return h})(u,c||[]);if(I.length!==0){t=null;const m=d().stackDepthCodeTraceDepth,p=m===-1?I:I.slice(0,m+1),h=Math.min(p.length,u.length);for(let y=0;y<h;y++)(async()=>{const A=ut(p[y].file,u[y].line,u[y].column);A&&(A.content!=null&&(p[y].code=A.content),A.file!=null&&(p[y].file=A.file))})();n.setOperationName("CollectExceptions");const f=l.message?`${l.name}: ${l.message}`:l.name;d().sfDebug&&console.log("error message is : ",f);const S=v.getInstance(),b=s.get(l);b?(S.setTraceIdFor(b,b),S.runWithSession(b,()=>{S.setTraceId(b),n.doSend(f,p)})):n.doSend(f,p),g?v.getInstance().runWithSession(g,()=>{n.doSend(f,p)}):n.doSend(f,p)}}}),e.on("error",i=>{console.error("[Worker Error]",i)}),e.on("exit",i=>{console.error(`[Worker] Exited with code ${i}`)}),e.unref();const r=Error,a=new Set;function o(...i){const c=Reflect.construct(r,i);Reflect.setPrototypeOf(c,o.prototype);try{const g=v.getInstance().getTraceId();s.set(c,g)}catch{}r.captureStackTrace&&r.captureStackTrace(c,o);const l=`${c.message}:${c.stack?.split(`
51
- `)[1]?.trim()}`;if(!a.has(l)){a.add(l),t=c;const g=v.getInstance().getTraceId();s.set(c,g),e.postMessage({type:"processException",error:c.message})}return c}o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(o,r),globalThis.Error=o}function Fe(n){return n=(n=(n=n.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function ut(n,e,t){const s=(function(a){a.startsWith("at ")&&(a=a.slice(3).trim());const o=a.match(/^(.*?)(:\d+)+(\.map)?$/);return o?o[1]:a})(n);if(!s||s==="<unknown>")return null;const r=s+".map";try{const a=L.readFileSync(r,"utf-8");if(a){const o=JSON.parse(a);let i=new fe.sourceMapExports.SourceMapConsumer(o).originalPositionFor({line:e,column:t});if(s&&i.source){const c=Fe(s),l=o.sources.findIndex(g=>Fe(g)===c);if(l===-1)d().sfDebug&&console.log(`Source file "${s}" not found in the source map.`);else{const g=o.sourcesContent[l],u=o.names.join(",");if(g)return{content:g.split(`
52
- `).slice(i.line-1,i.line+20).join(`
53
- `),name:u,file:i.source};d().sfDebug&&console.log(`No source content available for file "${s}".`)}}return{content:o.sourcesContent[0],name:o.names[0],file:o.file}}}catch(a){d().sfDebug&&console.log(`Cant read/parse "${r}: Error - ".`,a)}return null}function pt(n){return n?.split("/").pop()||"<unknown>"}function Oe(n,e){if(!n||typeof n!="object")return!1;for(const t of Object.values(n))if(typeof t=="string"&&t.includes(e)||typeof t=="object"&&Oe(t,e))return!0;return!1}let _e=!1;function we(n){if(!n)return;const e=n.toLowerCase().trim();return!!["1","true","yes","on"].includes(e)||!["0","false","no","off"].includes(e)&&void 0}function ce(n,e,t){return new Promise(s=>{try{const r=new URL(n),a=(r.protocol,B).request({method:"GET",hostname:r.hostname,port:r.port||(r.protocol==="https:"?443:80),path:r.pathname+(r.search||""),headers:e},o=>{o.resume(),o.statusCode&&o.statusCode>=200&&o.statusCode<400?s("ok"):s("http_error")});a.on("error",()=>s("error")),a.setTimeout(t,()=>{a.destroy(),s("timeout")}),a.end()}catch{s("error")}})}class It extends ${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,s={};return t!==void 0&&(s.isFromLocalService=t),s}async sendAppIdentifier(){this.serviceIdentifier.doSend({})}async doSend(t,s){this.sendAppIdentifier(),this.send(t,s)}async send(t,s){d().sfDebug&&console.log(" SENDING EXCEPTION...");const r=JSON.stringify(ee.encode(s)),a=this.normalizedSupplementalForGraphQL(),o=this.getVariables({exceptionMessage:t,traceJson:r,reentrancyGuardPreactive:!1,library:d().packageLibraryType,version:d().version,...a});W(this.endpoint,this.operationName,this.getQuery(),o)}getQuery(){return`
49
+ `}}const G={};class F{constructor({file:e,line:n,function:i,code:o,locals:s={},offender:l=!1,column:a}){f(this,"file");f(this,"line");f(this,"function");f(this,"code");f(this,"locals");f(this,"offender");f(this,"column");this.file=e,this.line=n,this.function=i,this.code=o,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 Se(t){r.getConfig().sfDebug&&console.log("Initializing Exception Interceptor...");try{const a=(function(){if(B!==void 0)return B;const g=process.env||{},c=ee(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(C=>!!g[C]))return B=!1;const I=(G.hostname?.()||g.HOSTNAME||"").toLowerCase();return I==="localhost"||I.endsWith(".local")||I.includes("local")?B=!0:B=!1})();t?.setSupplementalFields?.({isFromLocalService:a}),(async function(g){if(q)return;q=!0;const c=process.env||{};if(ee(c.SF_IS_LOCAL)===void 0)try{await(async function(d){const I=T("http://169.254.169.254/latest/meta-data/",{},d),C=T("http://metadata.google.internal/computeMetadata/v1/instance/",{"Metadata-Flavor":"Google"},d),p=T("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{Metadata:"true"},d);return(await Promise.allSettled([I,C,p])).some(u=>u.status==="fulfilled"&&(u.value==="ok"||u.value==="http_error"))})(150)&&B&&(B=!1,g?.setSupplementalFields?.({isFromLocalService:!1}))}catch{}})(t).catch(()=>{})}catch{}const e=new N.Worker(new URL("data:application/javascript;base64,aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gImluc3BlY3Rvci9wcm9taXNlcyI7Cm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IChsb2NhdGlvbiAmJiBsb2NhdGlvbi5zY3JpcHRJZCkgewogICAgICAgICAgY29uc3Qgc2NyaXB0SWQgPSBsb2NhdGlvbi5zY3JpcHRJZDsKICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHsgc2NyaXB0U291cmNlIH0gPSBhd2FpdCBzZXNzaW9uLnBvc3QoCiAgICAgICAgICAgICAgIkRlYnVnZ2VyLmdldFNjcmlwdFNvdXJjZSIsCiAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgc2NyaXB0SWQsCiAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc291cmNlTGluZXMgPSBzY3JpcHRTb3VyY2Uuc3BsaXQoIlxuIik7CiAgICAgICAgICAgIGNvZGUgPSBzb3VyY2VMaW5lc1tsb2NhdGlvbi5saW5lTnVtYmVyXSB8fCAiPG5vdCBjYXB0dXJlZD4iOwogICAgICAgICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgICAgIGlmIChnbG9iYWwuc2ZEZWJ1ZykgewogICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBzY3JpcHQgc291cmNlOiIsIGVycik7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIC8vIEZldGNoIGxvY2FsIHZhcmlhYmxlcyBpZiB0aGVyZSdzIGFuIG9iamVjdElkCiAgICAgICAgY29uc3QgbG9jYWxzID0gbG9jYWxTY29wZT8ub2JqZWN0Py5vYmplY3RJZAogICAgICAgICAgPyBhd2FpdCBmZXRjaExvY2FsVmFyaWFibGVzKHNlc3Npb24sIGxvY2FsU2NvcGUub2JqZWN0Lm9iamVjdElkKQogICAgICAgICAgOiB7fTsKCiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgIGZ1bmN0aW9uOiBmdW5jdGlvbk5hbWUgfHwgIjxhbm9ueW1vdXM+IiwKICAgIC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VzOwogICAgfQogIH0gY2F0Y2ggKGVycikgewogICAgaWYgKGdsb2JhbC5zZkRlYnVnKSB7CiAgICAgIGNvbnNvbGUuZXJyb3IoIltXb3JrZXJdIEZhaWxlZCB0byBmZXRjaCBsb2NhbCB2YXJpYWJsZXM6IiwgZXJyKTsKICAgIH0KICAgIHJldHVybiB7fTsKICB9Cn0KCnN0YXJ0RGVidWdnZXIoKS5jYXRjaCgoZXJyb3IpID0+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(p){return p?p.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),C=(function(p,u){const m=[];let h=-1,Z=-1;for(let b=0;b<p.length;b++){const y=Be(p[b].file);if(Z=b,y!=="<unknown>"){for(let A=0;A<u.length;A++){const v=u[A];if(pe(v,y)||typeof v.file=="string"&&v.file.includes(y)){h=A,W=0,r.getConfig().sfDebug&&console.log(`✅ Matched Frame Found: ${y} @ Debugger Frame ${A}`);break}}if(h!==-1)break}}if(h===-1)return W===10?(W=0,p):(++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=p[Z+b],A=u[h+b];m.push(new F({function:A?.function||y?.function||"<anonymous>",locals:A?.locals||y?.locals||{},file:y?.file||A?.file||"<unknown>",line:A?.line||y?.line||0,code:A?.code||y?.code||"<not captured>"}))}return m})(I,g||[]);if(C.length!==0){n=null;const p=r.getConfig().stackDepthCodeTraceDepth,u=p===-1?C:C.slice(0,p+1),m=Math.min(u.length,I.length);for(let y=0;y<m;y++)(async()=>{const A=Ge(u[y].file,I[y].line,I[y].column);A&&(A.content!=null&&(u[y].code=A.content),A.file!=null&&(u[y].file=A.file))})();t.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),t.doSend(h,u)})):t.doSend(h,u),d?r.ContextManager.getInstance().runWithSession(d,()=>{t.doSend(h,u)}):t.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 o=Error,s=new Set;function l(...a){const g=Reflect.construct(o,a);Reflect.setPrototypeOf(g,l.prototype);try{const d=r.ContextManager.getInstance().getTraceId();i.set(g,d)}catch{}o.captureStackTrace&&o.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(o.prototype,{constructor:{value:l,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(l,o),globalThis.Error=l}function Q(t){return t=(t=(t=t.replace(/^webpack:\/\/[^\/]+\/\.?\//,"")).replace(/^.*\/pages\//,"pages/")).replace(/\.(js|ts)$/,"")}function Ge(t,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})(t);if(!i||i==="<unknown>")return null;const o=i+".map";try{const s=X.readFileSync(o,"utf-8");if(s){const l=JSON.parse(s);let a=new O.sourceMapExports.SourceMapConsumer(l).originalPositionFor({line:e,column:n});if(i&&a.source){const g=Q(i),c=l.sources.findIndex(d=>Q(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 "${o}: Error - ".`,s)}return null}function Be(t){return t?.split("/").pop()||"<unknown>"}function pe(t,e){if(!t||typeof t!="object")return!1;for(const n of Object.values(t))if(typeof n=="string"&&n.includes(e)||typeof n=="object"&&pe(n,e))return!0;return!1}let q=!1;function ee(t){if(!t)return;const e=t.toLowerCase().trim();return!!["1","true","yes","on"].includes(e)||!["0","false","no","off"].includes(e)&&void 0}function T(t,e,n){return new Promise(i=>{try{const o=new URL(t),s=(o.protocol,G).request({method:"GET",hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+(o.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 ve extends r.BaseTransmitter{constructor(){super();f(this,"serviceIdentifier",new V);f(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 o=JSON.stringify(R.encode(i)),s=this.normalizedSupplementalForGraphQL(),l=this.getVariables({exceptionMessage:n,traceJson:o,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 Ve="getting request source code";var Q=(n=>(n.UNKNOWN="unknown",n.ANONYMOUS="anonymous",n.NOT_CAPTURED="not captured",n))(Q||{});const le="http:",ge="https:";function Ae(){return{capture_arguments:U(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:U(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:U(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:U(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:U(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:U(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}}function Ct(){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(n){try{const e=n.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 "${n}":`,e),null}}function U(n,e){if(!n)return e;const t=n.toLowerCase();return t==="true"||t==="1"||t==="yes"}const ye=new te.AsyncLocalStorage;function xe(n){ye.enterWith(n)}function Ce(){return ye.getStore()}function Me(){ye.enterWith(void 0)}function O(...n){const e={};for(const t of n)for(const s in t)t[s]!==void 0&&(e[s]=t[s]);return e}function J(n,e){try{const t=JSON.stringify(n).length/1048576;return t<=e?n:{_truncated:!0,_originalSizeMB:t.toFixed(2),_limitMB:e,_preview:JSON.stringify(n).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof n}}}const mt=nt.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:oe&&oe.tagName.toUpperCase()==="SCRIPT"&&oe.src||new URL("sf-veritas.cjs",document.baseURI).href);let Re=!1;function ht(){const n=d().sfDebug;if(Re)return void(n&&console.log("[patchNodeHttpInbound] Already installed, skipping."));let e;Re=!0;try{e=mt("node:http"),n&&console.log("[patchNodeHttpInbound] node:http required successfully.")}catch(r){return void console.error("Failed to require node:http:",r)}if(!e?.Server?.prototype)return void(n&&console.log("[patchNodeHttpInbound] http.Server.prototype not found."));const t=e.Server.prototype,s=t.emit;s&&!t.__sf_inbound_patched__?(Object.defineProperty(t,"__sf_inbound_patched__",{value:!0,enumerable:!1,configurable:!1,writable:!1}),n&&console.log("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),t.emit=function(r,...a){if(r!=="request")return n&&console.log(`[patchNodeHttpInbound] Passing through event: ${r}`),s.call(this,r,...a);const o=a[0],i=a[1],c=(function(m){const p={};if(!m)return p;for(const[h,f]of Object.entries(m))f!=null&&(Array.isArray(f)?p[h.toLowerCase()]=f.join(", "):p[h.toLowerCase()]=String(f));return p})(o?.headers),l=c["x-sf3-rid"],g=c["x-sf3-functionspancaptureoverride"];n&&(console.log("[patchNodeHttpInbound] Intercepted request event."),console.log("[patchNodeHttpInbound] Inbound headers:",c),console.log("[patchNodeHttpInbound] Trace header:",l),console.log("[patchNodeHttpInbound] FuncSpan override header:",g));const u=v.getInstance();u.setTraceId(l);const I=u.getTraceId();return n&&console.log("[patchNodeHttpInbound] Context traceId set:",I),u.runWith({inboundHeaders:c,...l?{traceId:l}:{}},()=>{l&&u.setTraceId(l),g&&(xe(g),n&&console.log("[patchNodeHttpInbound] FuncSpan override set:",g)),n&&console.log("[patchNodeHttpInbound] Running request handler in context.");const m=()=>{n&&console.log("[patchNodeHttpInbound] Response finished/closed for traceId:",u.getTraceId()),g&&(Me(),n&&console.log("[patchNodeHttpInbound] FuncSpan override cleared"))};return i.on("finish",m),i.on("close",m),s.call(this,r,o,i)})}):n&&console.log("[patchNodeHttpInbound] Already patched, skipping.")}class ft extends be{constructor(){super(),this.setOperationName("DomainsToNotPassHeaderTo")}async doSend(e){this.sendAppIdentifier(),this.send(e)}async send(e){const t=`
81
+ `}}const ne="getting request source code";var Y=(t=>(t.UNKNOWN="unknown",t.ANONYMOUS="anonymous",t.NOT_CAPTURED="not captured",t))(Y||{});const U="http:",E="https:",We=be.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:_&&_.tagName.toUpperCase()==="SCRIPT"&&_.src||new URL("sf-veritas.cjs",document.baseURI).href);let te=!1;function Ne(){const t=r.getConfig().sfDebug;if(te)return void(t&&console.log("[patchNodeHttpInbound] Already installed, skipping."));let e;te=!0;try{e=We("node:http"),t&&console.log("[patchNodeHttpInbound] node:http required successfully.")}catch(o){return void console.error("Failed to require node:http:",o)}if(!e?.Server?.prototype)return void(t&&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}),t&&console.log("[patchNodeHttpInbound] Patching http.Server.prototype.emit."),n.emit=function(o,...s){if(o!=="request")return t&&console.log(`[patchNodeHttpInbound] Passing through event: ${o}`),i.call(this,o,...s);const l=s[0],a=s[1],g=(function(u){const m={};if(!u)return m;for(const[h,Z]of Object.entries(u))Z!=null&&(Array.isArray(Z)?m[h.toLowerCase()]=Z.join(", "):m[h.toLowerCase()]=String(Z));return m})(l?.headers),c=g["x-sf3-rid"],d=g["x-sf3-functionspancaptureoverride"];t&&(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 C=I.getTraceId();t&&console.log("[patchNodeHttpInbound] Context traceId set:",C);const p=()=>I.runWith({inboundHeaders:g,...c?{traceId:c}:{}},()=>{c&&I.setTraceId(c),t&&console.log("[patchNodeHttpInbound] Running request handler in context.");const u=()=>{t&&console.log("[patchNodeHttpInbound] Response finished/closed for traceId:",I.getTraceId())};return a.on("finish",u),a.on("close",u),i.call(this,o,l,a)});if(!d)return p();try{return r.funcspanOverrideStorage.run(d,()=>p())}catch{return p()}}):t&&console.log("[patchNodeHttpInbound] Already patched, skipping.")}class Fe extends x{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
- `,s={apiKey:this.apiKey,serviceUuid:this.serviceUUID,domains:e};W(this.endpoint,this.operationName,t,s)}}class bt extends ${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:s,column:r,line:a,entrypoint:o,retryWithoutTraceId:i}=t,c=this.getVariables({name:s,column:r,line:a,entrypoint:o,retryWithoutTraceId:i});W(this.endpoint,this.operationName,this.getQuery(),c)}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();f(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:o,line:s,entrypoint:l,retryWithoutTraceId:a}=n,g=this.getVariables({name:i,column:o,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 At extends ${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 Ve extends r.BaseTransmitter{constructor(){super();f(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 s={data:{...t}};await W(this.endpoint,this.operationName,this.getQuery(),s)}}const de=[400,403];class yt{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)}),d().sfDebug&&console.log("[RequestInterceptor] Initialized with static excluded domains.")}extractIdsFromTraceHeader(e,t=this.HEADER_TRACING){let s;if(e instanceof Headers)s=e.get(t)??void 0;else{const a=t.toLowerCase();for(const[o,i]of Object.entries(e))if(o.toLowerCase()===a){s=i;break}}if(!s)return{};const r=s.split("/").filter(Boolean);return r.length<3?{}:{sessionId:r[0],pageVisitId:r[1],requestId:r[r.length-1]}}parseStackFrame(e){const t=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!t)return null;const[,s,r,a]=t;return{filePath:s,line:parseInt(r,10),column:parseInt(a,10)}}async getOriginalPosition(e,t,s){let r={source:e,line:t,column:s,name:null};const a=e+".map";try{const o=JSON.parse(L.readFileSync(a,"utf-8"));let i=(await new fe.sourceMapExports.SourceMapConsumer(o)).originalPositionFor({line:t,column:s});i.source&&(r=i)}catch(o){d().sfDebug&&console.error(`Could not read/parse map file at ${a}:`,o)}return{originalPos:r}}captureFirstUserLines(e,t=10,s=!1){const r=d().sfDebug?10:t,a=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(a,r);const o=new Error(Ve);Ve in Error&&Error.captureStackTrace(o,this.captureFirstUserLines);const i=o.stack||"";Error.stackTraceLimit=a;const c=i.split(`
125
- `).slice(1),l=[];for(const g of c)if(!(g.includes("node:internal")||g.includes("internal/modules")||g.includes("internal/process")||g.includes("node_modules")||g.includes(".next/server/chunks")||g.includes("RequestInterceptor")||g.includes("contextManager")||g.includes("setupConfig"))&&(l.push(g.trim()),l.length>=t))break;for(const g of l){const u=this.parseStackFrame(g);u?(async()=>{const{originalPos:I}=await this.getOriginalPosition(u.filePath,u.line,u.column);if(I){d().sfDebug&&console.log("[RequestInterceptor] First user code line:",I);const m={line:I.line?.toString()||Q.UNKNOWN,column:I.column?.toString()||Q.NOT_CAPTURED,name:I.name||Q.NOT_CAPTURED,entrypoint:I.source,retryWithoutTraceId:s};e.doSend(m)}})():d().sfDebug&&console.error("Could not parse stack line:",g)}}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!ze.some(t=>new RegExp(`^${t.replace(/\*/g,".*")}$`).test(e))}addTracingHeaders(e,t){const s=new URL(t).hostname,r=this.shouldPropagateHeaders(s);return r?this.addTracingHeader(e,t):d().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${s}`),r}addTracingHeader(e,t){const s=Ce();if(s){const i=Ie(s);if(i&&i.sample_rate===0)return void(d().sfDebug&&console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${t}`))}const r=this.contextManager.getOrSetSfTraceId(),a=this.contextManager.getOrSetPageVisitUUID(),o=V();e.set(this.HEADER_TRACING,`${r}/${a}/${o}`),d().sfDebug&&console.log(`[RequestInterceptor] Added tracing header for ${t}`)}patchFetch(e,t){const s=globalThis.fetch;typeof s=="function"?globalThis.fetch=async(r,a)=>{const o=new Headers(a?.headers);if(o.get(this.HEADER_LOG_GUARD)==="true"||o.get(this.HEADER_PRINT_GUARD)==="true"||o.get(this.HEADER_EXCEPTION_GUARD)==="true")return s(r,a);this.captureFirstUserLines(e);const i=Date.now();let c;typeof r=="string"||r instanceof URL?c=r.toString():r instanceof Request?(c=r.url,r.headers.forEach((p,h)=>{o.set(h,p)})):d().sfDebug&&console.error("[Sailfish RequestInterceptor] Invalid fetch input."),d().sfDebug&&console.log("[RequestInterceptor] Fetching request to:",c);const l=new URL(c).hostname,g=new Headers(o),u=this.addTracingHeaders(o,c),I={...a,headers:o};let m;try{let p=!1;this.addTracingHeaders(g,c),m=await s(c,I),u&&de.includes(m.status)?(m=await s(c,{...a,headers:g}),p=!0,this.captureFirstUserLines(e,10,p)):this.contextManager.addSupportedDomains(l);const h=Date.now();d().sfDebug&&console.log(`[RequestInterceptor] Fetch completed: ${c}, Status: ${m.status}, Duration: ${h-i}ms`);const{sessionId:f,pageVisitId:S,requestId:b}=this.extractIdsFromTraceHeader(o);return t.doSend({apiKey:d().apiKey,requestId:b,pageVisitId:S,recordingSessionId:f,serviceUuid:d().serviceUUID,timestampStart:i.toString(),timestampEnd:h.toString(),responseCode:m.status,success:!0,error:null,url:c,method:I.method||"GET",retryWithoutTraceId:p,parentSpanId:j()}),m}catch(p){const h=Date.now();d().sfDebug&&console.error(`[RequestInterceptor] Fetch failed: ${c}, Error: ${p}, Duration: ${h-i}ms`)}}:d().sfDebug&&console.error("[RequestInterceptor] Fetch not available.")}patchHttp(e,t){if(d().sfDebug&&console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."),!B||typeof B.request!="function")return void(d().sfDebug&&console.log("[RequestInterceptor] HTTP/HTTPS not available."));const s=B.request.bind(B),r=B.request.bind(B);B.request=function(a,o){let i;try{if(typeof a=="string"){const l=new URL(a);i={protocol:l.protocol||le,hostname:l.hostname,path:l.pathname+l.search,headers:{}}}else a instanceof URL?i={protocol:a.protocol||le,hostname:a.hostname,path:a.pathname+a.search,headers:{}}:(i={...a},i.protocol||(i.protocol=le));if(i.headers){const l=`${i.protocol}//${i.hostname}`;this.addTracingHeaders(i.headers,l),this.captureFirstUserLines(e)}else d().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTP request options. Skipping header addition.")}catch(l){throw d().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTP request options:",l),l}let c=!1;return s(i,l=>{const g=`${i.protocol}//${i.hostname}`;if(i.headers&&this.shouldPropagateHeaders(new URL(g).hostname)&&de.includes(l.statusCode||0)){i.hostname;const p={...i,headers:{...i.headers}};delete p.headers[this.HEADER_TRACING],s(p,o),c=!0,this.captureFirstUserLines(e,10,c)}const{sessionId:u,pageVisitId:I,requestId:m}=this.extractIdsFromTraceHeader(i.headers);t.doSend({apiKey:d().apiKey,requestId:m,pageVisitId:I,recordingSessionId:u,serviceUuid:d().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:l.statusCode||0,success:!!l.statusCode&&l.statusCode<400,error:null,url:g,method:i.method||"GET",retryWithoutTraceId:c,parentSpanId:j()}),o?.(l)})},B.request=function(a,o){let i;try{if(typeof a=="string"){const l=new URL(a);i={protocol:l.protocol||ge,hostname:l.hostname,path:l.pathname+l.search,headers:{}}}else a instanceof URL?i={protocol:a.protocol||ge,hostname:a.hostname,path:a.pathname+a.search,headers:{}}:(i={...a},i.protocol||(i.protocol=ge));if(i.headers){const l=`${i.protocol}//${i.hostname}`;this.addTracingHeaders(i.headers,l)}else d().sfDebug&&console.warn("[RequestInterceptor] No headers found in HTTPS request options. Skipping header addition.")}catch(l){throw d().sfDebug&&console.error("[RequestInterceptor] Error while processing HTTPS request options:",l),l}let c=!1;return r(i,l=>{const g=`${i.protocol}//${i.hostname}`;if(i.headers&&this.shouldPropagateHeaders(new URL(g).hostname)&&de.includes(l.statusCode||0)){const p={...i,headers:{...i.headers}};delete p.headers[this.HEADER_TRACING],r(p,o),c=!0,this.captureFirstUserLines(e,10,c)}const{sessionId:u,pageVisitId:I,requestId:m}=this.extractIdsFromTraceHeader(i.headers);t.doSend({apiKey:d().apiKey,requestId:m,pageVisitId:I,recordingSessionId:u,serviceUuid:d().serviceUUID,timestampStart:Date.now().toString(),timestampEnd:Date.now().toString(),responseCode:l.statusCode||0,success:!!l.statusCode&&l.statusCode<400,error:null,url:g,method:i.method||"GET",retryWithoutTraceId:c,parentSpanId:j()}),o?.(l)})},d().sfDebug&&console.log("✅ HTTP and HTTPS request methods patched globally.")}tryPatch(e,t){try{require.resolve(t),e(),console.log(`[RequestInterceptor] Patched ${t}`)}catch(s){console.warn(`[RequestInterceptor] Could not patch ${t}: ${s.message}`)}}getExcludedDomains(){return[...this.contextManager.getExcludedDomains()]}}class St extends be{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 z=[400,403];class He{constructor(e=[]){f(this,"HEADER_TRACING","X-Sf3-Rid");f(this,"HEADER_LOG_GUARD","reentrancy_guard_logging_preactive");f(this,"HEADER_PRINT_GUARD","reentrancy_guard_print_preactive");f(this,"HEADER_EXCEPTION_GUARD","reentrancy_guard_exception_preactive");f(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 o=i.split("/").filter(Boolean);return o.length<3?{}:{sessionId:o[0],pageVisitId:o[1],requestId:o[o.length-1]}}parseStackFrame(e){const n=/\((.*):(\d+):(\d+)\)$/.exec(e.trim());if(!n)return null;const[,i,o,s]=n;return{filePath:i,line:parseInt(o,10),column:parseInt(s,10)}}async getOriginalPosition(e,n,i){let o={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 O.sourceMapExports.SourceMapConsumer(l)).originalPositionFor({line:n,column:i});a.source&&(o=a)}catch(l){r.getConfig().sfDebug&&console.error(`Could not read/parse map file at ${s}:`,l)}return{originalPos:o}}captureFirstUserLines(e,n=10,i=!1){const o=r.getConfig().sfDebug?10:n,s=Error.stackTraceLimit;Error.stackTraceLimit=Math.max(s,o);const l=new Error(ne);ne 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:C}=await this.getOriginalPosition(I.filePath,I.line,I.column);if(C){r.getConfig().sfDebug&&console.log("[RequestInterceptor] First user code line:",C);const p={line:C.line?.toString()||Y.UNKNOWN,column:C.column?.toString()||Y.NOT_CAPTURED,name:C.name||Y.NOT_CAPTURED,entrypoint:C.source,retryWithoutTraceId:i};e.doSend(p)}})():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,o=this.shouldPropagateHeaders(i);return o?this.addTracingHeader(e,n):r.getConfig().sfDebug&&console.error(`[RequestInterceptor] Excluded domain: ${i}`),o}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 o=this.contextManager.getOrSetSfTraceId(),s=this.contextManager.getOrSetPageVisitUUID(),l=r.v4();e.set(this.HEADER_TRACING,`${o}/${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(o,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(o,s);this.captureFirstUserLines(e);const a=Date.now();let g;typeof o=="string"||o instanceof URL?g=o.toString():o instanceof Request?(g=o.url,o.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),C={...s,headers:l};let p;try{let u=!1;this.addTracingHeaders(d,g),p=await i(g,C),I&&z.includes(p.status)?(p=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: ${p.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:p.status,success:!0,error:null,url:g,method:C.method||"GET",retryWithoutTraceId:u,parentSpanId:r.getCurrentFunctionSpanId()}),p}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),o=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||U,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?a={protocol:s.protocol||U,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(a={...s},a.protocol||(a.protocol=U));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)&&z.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:C,requestId:p}=this.extractIdsFromTraceHeader(a.headers);n.doSend({apiKey:r.getConfig().apiKey,requestId:p,pageVisitId:C,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||E,hostname:c.hostname,path:c.pathname+c.search,headers:{}}}else s instanceof URL?a={protocol:s.protocol||E,hostname:s.hostname,path:s.pathname+s.search,headers:{}}:(a={...s},a.protocol||(a.protocol=E));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 o(a,c=>{const d=`${a.protocol}//${a.hostname}`;if(a.headers&&this.shouldPropagateHeaders(new URL(d).hostname)&&z.includes(c.statusCode||0)){const u={...a,headers:{...a.headers}};delete u.headers[this.HEADER_TRACING],o(u,l),g=!0,this.captureFirstUserLines(e,10,g)}const{sessionId:I,pageVisitId:C,requestId:p}=this.extractIdsFromTraceHeader(a.headers);n.doSend({apiKey:r.getConfig().apiKey,requestId:p,pageVisitId:C,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 Ye extends x{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,88 +142,6 @@
142
142
  gitSha: $gitSha,
143
143
  )
144
144
  }
145
- `,t=this.getVariables({serviceIdentifier:d().serviceIdentifier,serviceVersion:d().serviceVersion,serviceAdditionalMetadata:d().serviceAdditionalMetadata,gitSha:d().gitSha||""});W(this.endpoint,this.operationName,e,t)}}class Nt{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)se.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 s=this.hasSailfishFiles?Ae():{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},r=this._getDirectoryConfig(e),a=G.normalize(e),o=this.fileConfigs.get(a)||{};let i={};if(t){const c=this.functionConfigs.get(a);c&&(i=c.get(t)||{})}return O(s,r,o,i)}async _walkDirectory(e,t){try{const s=se.readdirSync(e,{withFileTypes:!0});for(const r of s){const a=G.join(e,r.name);r.isFile()&&r.name===".sailfish"?t.push(a):r.name==="node_modules"||r.isDirectory()&&r.name.startsWith(".")&&r.name!==".sailfish"||r.isDirectory()&&await this._walkDirectory(a,t)}}catch(s){this.debug&&console.error(`[FuncSpan ConfigLoader] Error walking directory ${e}:`,s)}}async _loadConfigFile(e){try{const t=se.readFileSync(e,"utf-8"),s=G.dirname(e);let r=null;try{r=JSON.parse(t)}catch{try{r=require("js-yaml").load(t)}catch(a){return void(this.debug&&console.error(`[FuncSpan ConfigLoader] Failed to parse ${e} as JSON or YAML:`,a))}}if(!r)return;r.default&&this.directoryConfigs.set(s,r.default),r.files&&await this._expandFileGlobs(s,r.files,r.default||{}),r.functions&&this._storeFunctionConfigs(s,r.functions,r.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${s}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions||{}).length}`))}catch(t){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,t)}}async _expandFileGlobs(e,t,s){for(const[r,a]of Object.entries(t))try{const o=G.join(e,r),i=await ot.glob(o,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${i.length} files`);for(const c of i){const l=G.normalize(c),g=O(s,a);this.fileConfigs.set(l,g),this.debug&&i.length<=5&&console.log(`[FuncSpan ConfigLoader] - ${c}`)}}catch(o){this.debug&&console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`,o)}}_storeFunctionConfigs(e,t,s){for(const[r,a]of Object.entries(t)){const o=r.split("::");if(o.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);continue}const[i,c]=o,l=G.normalize(G.join(e,i));this.functionConfigs.has(l)||this.functionConfigs.set(l,new Map);const g=this.functionConfigs.get(l),u=O(s,a);g.set(c,u),this.debug&&console.log(`[FuncSpan ConfigLoader] Function config: ${l}::${c}`)}}async _resolveInheritance(){}_getDirectoryConfig(e){let t=G.dirname(G.normalize(e));const s=[];for(;t&&t!==G.dirname(t);){const r=this.directoryConfigs.get(t);r&&s.unshift(r),t=G.dirname(t)}return s.reduce((r,a)=>O(r,a),{})}}let D=null;async function Te(n,e){D=new Nt(n,e),await D.loadAllConfigs()}function He(n,e){return D?D.getConfig(n,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),Ae())}function $e(){return D!==null}function R(n,e){const t=process.env[n];return t===void 0?e:t==="true"||t==="1"}function Ue(n,e){const t=process.env[n];if(t===void 0)return e;const s=parseFloat(t);return isNaN(s)?e:s}function Se(){return{enabled:R("SF_WORKER_POOL_ENABLED",!0),trackFs:R("SF_WORKER_POOL_TRACK_FS",!1),trackDns:R("SF_WORKER_POOL_TRACK_DNS",!0),trackCrypto:R("SF_WORKER_POOL_TRACK_CRYPTO",!1),trackZlib:R("SF_WORKER_POOL_TRACK_ZLIB",!1),captureArguments:R("SF_WORKER_POOL_CAPTURE_ARGUMENTS",!0),captureReturnValue:R("SF_WORKER_POOL_CAPTURE_RETURN_VALUE",!0),argLimitMb:Ue("SF_WORKER_POOL_ARG_LIMIT_MB",1),returnLimitMb:Ue("SF_WORKER_POOL_RETURN_LIMIT_MB",1)}}function x(n){const e=Se();if(!e.enabled)return!1;switch(n){case"fs":return e.trackFs;case"dns":return e.trackDns;case"crypto":return e.trackCrypto;case"zlib":return e.trackZlib;default:return!1}}function je(n,e,t,s){let r;try{switch(n){case"fs":r=(function(a,o){const i={};switch(a){case"readFile":case"writeFile":case"appendFile":i.path=String(o[0]||""),o[1]&&typeof o[1]=="object"?(i.encoding=o[1].encoding||null,i.flag=o[1].flag||null):typeof o[1]=="string"&&(i.encoding=o[1]),a!=="writeFile"&&a!=="appendFile"||(Buffer.isBuffer(o[1])?(i.dataType="Buffer",i.dataSize=o[1].length):typeof o[1]=="string"&&(i.dataType="string",i.dataSize=o[1].length));break;case"readdir":case"stat":case"lstat":case"access":case"chmod":case"mkdir":case"rmdir":case"unlink":i.path=String(o[0]||""),o[1]&&typeof o[1]=="object"&&(i.options={...o[1]},delete i.options.callback);break;case"rename":i.oldPath=String(o[0]||""),i.newPath=String(o[1]||"");break;case"open":i.path=String(o[0]||""),i.flags=o[1],i.mode=o[2];break;case"close":case"fstat":i.fd=o[0];break;case"read":case"write":i.fd=o[0],Buffer.isBuffer(o[1])&&(i.bufferSize=o[1].length),i.offset=o[2],i.length=o[3],i.position=o[4];break;default:i.argsCount=o.length-1}return i})(e,t);break;case"dns":r=(function(a,o){const i={};switch(a){case"lookup":i.hostname=String(o[0]||""),typeof o[1]=="object"?(i.family=o[1].family,i.all=o[1].all):typeof o[1]=="number"&&(i.family=o[1]);break;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":i.hostname=String(o[0]||"");break;case"reverse":i.ip=String(o[0]||"");break;default:i.argsCount=o.length-1}return i})(e,t);break;case"crypto":r=(function(a,o){const i={};switch(a){case"pbkdf2":i.passwordType=typeof o[0],i.saltType=typeof o[1],i.iterations=o[2],i.keylen=o[3],i.digest=o[4];break;case"scrypt":i.passwordType=typeof o[0],i.saltType=typeof o[1],i.keylen=o[2],typeof o[3]=="object"&&(i.N=o[3].N,i.r=o[3].r,i.p=o[3].p);break;case"randomBytes":i.size=o[0];break;case"generateKeyPair":i.type=o[0],typeof o[1]=="object"&&(i.modulusLength=o[1].modulusLength,i.namedCurve=o[1].namedCurve);break;default:i.argsCount=o.length-1}return i})(e,t);break;case"zlib":r=(function(a,o){const i={};return Buffer.isBuffer(o[0])?(i.inputType="Buffer",i.inputSize=o[0].length):typeof o[0]=="string"?(i.inputType="string",i.inputSize=o[0].length):i.inputType=typeof o[0],o[1]&&typeof o[1]=="object"&&typeof o[1]!="function"&&(i.options={...o[1]}),i})(0,t);break;default:return null}return s>0?J(r,s):r}catch{return{error:"Failed to capture arguments",argsCount:t.length-1}}}function Qe(n,e,t,s){let r;try{switch(n){case"fs":r=(function(a,o){if(!o)return null;switch(a){case"readFile":return Buffer.isBuffer(o)?{type:"Buffer",size:o.length}:typeof o=="string"?{type:"string",size:o.length}:{type:typeof o};case"readdir":return{count:Array.isArray(o)?o.length:0,items:o};case"stat":case"lstat":case"fstat":return{size:o.size,mode:o.mode,isFile:o.isFile(),isDirectory:o.isDirectory()};case"open":return{fd:o};case"read":return{bytesRead:o};case"write":return{bytesWritten:o};default:return o}})(e,t);break;case"dns":r=(function(a,o){if(!o)return null;switch(a){case"lookup":return Array.isArray(o)?{count:o.length,addresses:o}:o;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":return{count:Array.isArray(o)?o.length:0,records:o};case"reverse":return{hostnames:o};default:return o}})(e,t);break;case"crypto":r=(function(a,o){if(!o)return null;switch(a){case"pbkdf2":case"scrypt":case"randomBytes":return Buffer.isBuffer(o)?{type:"Buffer",size:o.length}:{type:typeof o};case"generateKeyPair":return{hasPublicKey:!!o?.publicKey,hasPrivateKey:!!o?.privateKey};default:return o}})(e,t);break;case"zlib":r=(function(a,o){return o?Buffer.isBuffer(o)?{type:"Buffer",size:o.length}:typeof o=="string"?{type:"string",size:o.length}:{type:typeof o}:null})(0,t);break;default:return null}return s>0?J(r,s):r}catch{return{error:"Failed to capture result",type:typeof t}}}function vt(n){return n.operationType==="worker_pool"}class qe extends ${constructor(){super(),this.operationName="CollectFunctionSpans"}send(e){const t=d().sfDebug;t&&console.log(`[FunctionSpanTransmitter] Preparing to send ${e.length} function span(s)`);for(const s of e)try{if(vt(s)){this.sendWorkerPoolSpan(s,t);continue}const r=s;let a;if(r.result!==void 0&&r.result!==null){const i=typeof r.result;a=JSON.stringify({type:i,has_value:!0,value:r.result})}else a=r.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const o=this.getVariables({library:"JS/TS BACKEND",version:d().version,spanId:r.spanId,parentSpanId:r.parentSpanId,filePath:r.filePath,lineNumber:r.metadata.line,columnNumber:r.metadata.column,functionName:r.functionName,arguments:JSON.stringify(r.args||{}),returnValue:a,startTimeNs:(1e6*Date.now()-1e6*r.duration).toString(),durationNs:(1e6*r.duration).toString()});t&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(o,null,2))),W(this.endpoint,this.operationName,this.getQuery(),o),t&&console.log(`[FunctionSpanTransmitter] Queued function span for ${r.functionName}`)}catch(r){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${s.functionName}:`,r)}}sendWorkerPoolSpan(e,t){try{let s;if(e.result!==void 0&&e.result!==null){const a=typeof e.result;s=JSON.stringify({type:a,has_value:!0,value:e.result})}else s=e.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const r=this.getVariables({library:"JS/TS BACKEND",version:d().version,spanId:e.spanId,operationName:e.operationName,moduleName:e.moduleName,methodName:e.methodName,startTimeNs:e.startTimeNs,durationNs:e.durationNs,arguments:JSON.stringify(e.args||{}),returnValue:s,error:e.error,pid:e.pid,threadId:e.threadId});t&&(console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${e.operationName}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(r,null,2))),W(this.endpoint,"CollectWorkerPoolSpans",this.getWorkerPoolQuery(),r),t&&console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${e.operationName}`)}catch(s){console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${e.operationName}:`,s)}}getWorkerPoolQuery(){return`
146
- mutation CollectWorkerPoolSpans(
147
- $apiKey: String!,
148
- $serviceUuid: String!,
149
- $sessionId: String!,
150
- $timestampMs: String!,
151
- $library: String!,
152
- $version: String!,
153
- $spanId: String!,
154
- $operationName: String!,
155
- $moduleName: String!,
156
- $methodName: String!,
157
- $startTimeNs: String!,
158
- $durationNs: String!,
159
- $parentSpanId: String,
160
- $arguments: String,
161
- $returnValue: String,
162
- $error: String,
163
- $pid: Int,
164
- $threadId: Int
165
- ) {
166
- collectWorkerPoolSpans(
167
- apiKey: $apiKey,
168
- serviceUuid: $serviceUuid,
169
- sessionId: $sessionId,
170
- timestampMs: $timestampMs,
171
- library: $library,
172
- version: $version,
173
- spanId: $spanId,
174
- operationName: $operationName,
175
- moduleName: $moduleName,
176
- methodName: $methodName,
177
- startTimeNs: $startTimeNs,
178
- durationNs: $durationNs,
179
- parentSpanId: $parentSpanId,
180
- arguments: $arguments,
181
- returnValue: $returnValue,
182
- error: $error,
183
- pid: $pid,
184
- threadId: $threadId
185
- )
186
- }
187
- `}getQuery(){return`
188
- ${this.queryType} ${this.operationName}(
189
- $apiKey: String!,
190
- $serviceUuid: String!,
191
- $sessionId: String!,
192
- $timestampMs: String!,
193
- $parentSpanId: String,
194
- $library: String!,
195
- $version: String!,
196
- $spanId: String!,
197
- $filePath: String!,
198
- $lineNumber: Int!,
199
- $columnNumber: Int!,
200
- $functionName: String!,
201
- $arguments: String!,
202
- $returnValue: String,
203
- $startTimeNs: String!,
204
- $durationNs: String!
205
- ) {
206
- ${this.queryName}(
207
- apiKey: $apiKey,
208
- serviceUuid: $serviceUuid,
209
- sessionId: $sessionId,
210
- timestampMs: $timestampMs,
211
- parentSpanId: $parentSpanId,
212
- library: $library,
213
- version: $version,
214
- spanId: $spanId,
215
- filePath: $filePath,
216
- lineNumber: $lineNumber,
217
- columnNumber: $columnNumber,
218
- functionName: $functionName,
219
- arguments: $arguments,
220
- returnValue: $returnValue,
221
- startTimeNs: $startTimeNs,
222
- durationNs: $durationNs
223
- )
224
- }
225
- `}}let ue=null;function q(n,e,t,s,r){const a=H(),o=a?.sfDebug||!1;o&&console.log(`[WorkerPool] Capturing ${n}.${e}`);const i=Se(),c=v.getInstance().getCurrentFunctionSpanId(),l=V();o&&console.log(`[WorkerPool] Span ID: ${l}, Parent: ${c||"none"}`);const g=new te.AsyncResource("WorkerPoolOperation"),u=process.hrtime.bigint();let I=null;i.captureArguments&&(I=je(n,e,s,i.argLimitMb));const m=s.findIndex(f=>typeof f=="function");if(m===-1)return o&&console.log(`[WorkerPool] No callback found for ${n}.${e}`),t.apply(r,s);const p=s[m],h=[...s];return h[m]=function(f,...S){const b=process.hrtime.bigint()-u,y=Number(b)/1e6;p(f,...S),g.runInAsyncScope(()=>{o&&console.log(`[WorkerPool] ${n}.${e} completed in ${y.toFixed(3)}ms (${b}ns)`);let A=null,Z=null;f?Z=f?.message||String(f):i.captureReturnValue&&S.length>0&&(A=Qe(n,e,S[0],i.returnLimitMb)),me({operationType:"worker_pool",operationName:`${n}.${e}`,moduleName:n,methodName:e,duration:y,durationNs:b.toString(),startTimeNs:u.toString(),args:I,result:A,error:Z,spanId:l,parentSpanId:c,pid:process.pid,threadId:w.threadId})}),g.emitDestroy()},t.apply(r,h)}function Gt(n,e,t,s,r){const a=H(),o=a?.sfDebug||!1;o&&console.log(`[WorkerPool] Capturing ${n}.${e} (Promise)`);const i=Se(),c=v.getInstance().getCurrentFunctionSpanId(),l=V();o&&console.log(`[WorkerPool] Span ID: ${l}, Parent: ${c||"none"}`);const g=process.hrtime.bigint();let u=null;return i.captureArguments&&(u=je(n,e,s,i.argLimitMb)),t.apply(r,s).then(I=>{const m=process.hrtime.bigint()-g,p=Number(m)/1e6;o&&console.log(`[WorkerPool] ${n}.${e} completed in ${p.toFixed(3)}ms (${m}ns)`);let h=null;return i.captureReturnValue&&(h=Qe(n,e,I,i.returnLimitMb)),me({operationType:"worker_pool",operationName:`${n}.${e}`,moduleName:n,methodName:e,duration:p,durationNs:m.toString(),startTimeNs:g.toString(),args:u,result:h,error:null,spanId:l,parentSpanId:c,pid:process.pid,threadId:w.threadId}),I},I=>{const m=process.hrtime.bigint()-g,p=Number(m)/1e6;throw o&&console.log(`[WorkerPool] ${n}.${e} failed in ${p.toFixed(3)}ms: ${I?.message||I}`),me({operationType:"worker_pool",operationName:`${n}.${e}`,moduleName:n,methodName:e,duration:p,durationNs:m.toString(),startTimeNs:g.toString(),args:u,result:null,error:I?.message||String(I),spanId:l,parentSpanId:c,pid:process.pid,threadId:w.threadId}),I})}function me(n){const e=H(),t=e?.sfDebug||!1;t&&console.log("[WorkerPool] Capturing span:",{operation:n.operationName,duration:`${n.duration}ms`,error:n.error,spanId:n.spanId,parentSpanId:n.parentSpanId}),process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
226
- ⚙️ Worker Pool Operation:`,{operation:n.operationName,duration:`${n.duration.toFixed(2)}ms`,arguments:n.args,result:n.error?`Error: ${n.error}`:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId||"none"});const s=process.env.SF_FUNCSPAN_JSONL_FILE;if(s)try{const r=s==="true"||s==="1"?"funcspans.jsonl":s,a=Date.now(),o=process.hrtime.bigint(),i=BigInt(n.startTimeNs),c=Number(o-i)/1e6,l=new Date(a-c).toISOString(),g=JSON.stringify({timestamp:l,operationType:n.operationType,operationName:n.operationName,moduleName:n.moduleName,methodName:n.methodName,duration:n.duration,durationNs:n.durationNs,startTimeNs:n.startTimeNs,arguments:n.args,returnValue:n.error?{error:String(n.error)}:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId,pid:n.pid,threadId:n.threadId})+`
227
- `;L.appendFileSync(r,g,"utf-8")}catch(r){console.error("[WorkerPool] Error writing to JSONL file:",r)}if(t&&console.log("[WorkerPool] Sending span to transmitter"),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(ue||(ue=new qe),ue).send([n]),t&&console.log("[WorkerPool] Span sent successfully")}catch(r){t&&console.error("[WorkerPool] Error sending span:",r)}}const Zt=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],Ee=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Bt=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Wt=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let Ke=!1,ke=!1;function Ft(){if(!ke)try{const n=require("node:dns");if(n.__sf_worker_pool_patched__)return;Object.defineProperty(n,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of Ee)if(typeof n[e]=="function"){const t=n[e];n[e]=function(...s){const r=s[0];return typeof r=="string"&&(r==="localhost"||r==="127.0.0.1")?t.apply(this,s):typeof s[s.length-1]=="function"?q("dns",e,t,s,this):t.apply(this,s)},Object.defineProperty(n[e],"name",{value:e,writable:!1})}(function(e){if(!e.promises)return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises not available, skipping"));if(!e.promises.__sf_worker_pool_patched__){Object.defineProperty(e.promises,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Ee)if(typeof e.promises[t]=="function"){const s=e.promises[t];e.promises[t]=function(...r){const a=r[0];return typeof a!="string"||a!=="localhost"&&a!=="127.0.0.1"?Gt("dns",t,s,r,this):s.apply(this,r)},Object.defineProperty(e.promises[t],"name",{value:t,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(n),ke=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(n){console.error("[WorkerPool] Error patching dns module:",n)}}let Ye=!1,Je=!1,he=!1;function De(){if(he)return;const n=process.env.SF_DEBUG==="true";n&&console.log("[WorkerPool] Initializing worker pool patching..."),x("fs")&&(n&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!Ke)try{const e=require("node:fs");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Zt)if(typeof e[t]=="function"){const s=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?q("fs",t,s,r,this):s.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}Ke=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] fs module patched successfully")}catch(e){console.error("[WorkerPool] Error patching fs module:",e)}})()),x("dns")&&(n&&console.log("[WorkerPool] Patching dns module..."),Ft()),x("crypto")&&(n&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!Ye)try{const e=require("node:crypto");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Bt)if(typeof e[t]=="function"){const s=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?q("crypto",t,s,r,this):s.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}Ye=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] crypto module patched successfully")}catch(e){console.error("[WorkerPool] Error patching crypto module:",e)}})()),x("zlib")&&(n&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!Je)try{const e=require("node:zlib");if(e.__sf_worker_pool_patched__)return;Object.defineProperty(e,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const t of Wt)if(typeof e[t]=="function"){const s=e[t];e[t]=function(...r){return typeof r[r.length-1]=="function"?q("zlib",t,s,r,this):s.apply(this,r)},Object.defineProperty(e[t],"name",{value:t,writable:!1})}Je=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),he=!0,n&&console.log("[WorkerPool] Worker pool patching initialized")}function Le(){return he}let pe=null;function M(n){const e=H(),t=e?.sfDebug||!1;t&&console.log("[FuncSpan] captureSpanData called for:",{function:n.functionName,file:n.filePath,duration:`${n.duration}ms`,async:n.async,error:n.error,spanId:n.spanId});const s={functionName:n.functionName,filePath:n.filePath,metadata:n.metadata,args:n.args,result:n.result,error:n.error,duration:n.duration,durationNs:n.durationNs,async:n.async,spanId:n.spanId,parentSpanId:n.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
228
- 📊 Function Span:`,{function:`${n.functionName} (${n.filePath}:${n.metadata.line}:${n.metadata.column})`,duration:`${n.duration.toFixed(2)}ms`,arguments:n.args,result:n.error?`Error: ${n.error}`:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId||"none"});const r=process.env.SF_FUNCSPAN_JSONL_FILE;if(r)try{const a=r==="true"||r==="1"?"funcspans.jsonl":r,o=Date.now(),i=process.hrtime.bigint(),c=BigInt(n.startTimeNs),l=Number(i-c)/1e6,g=new Date(o-l).toISOString(),u=JSON.stringify({timestamp:g,functionName:n.functionName,filePath:n.filePath,line:n.metadata.line,column:n.metadata.column,duration:n.duration,durationNs:n.durationNs,startTimeNs:n.startTimeNs,arguments:n.args,returnValue:n.error?{error:String(n.error)}:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId,async:n.async,pid:n.pid,threadId:n.threadId})+`
229
- `;L.appendFileSync(a,u,"utf-8")}catch(a){console.error("[FuncSpan] Error writing to JSONL file:",a)}if(t&&console.log("[FuncSpan] Sending function span to transmitter:",s),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(pe||(pe=new qe),pe).send([s]),t&&console.log("[FuncSpan] Function span sent successfully")}catch(a){t&&console.error("[FuncSpan] Error sending function span:",a)}}exports.transformFunctionSpans=fe.transformFunctionSpans,exports.ContextManager=v,exports.addOrUpdateMetadata=function(n,e={},t,s=!1){const r=d();new We(r.apiKey).addOrUpdateMetadata(n,e,t,s)},exports.captureFunctionSpan=function(n,e,t,s){const r=function(...a){const o=H(),i=o?.sfDebug||!1;i&&console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${t}::${e}`);const c=(function(h,f){const S=Ce();if(S){const b=Ie(S);if(b)return process.env.SF_DEBUG==="true"&&console.log(`[FuncSpan] Using HTTP header override for ${h}::${f}`),b}try{return He(h,f)}catch{return{sample_rate:process.env.SF_FUNCSPAN_SAMPLE_RATE?parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE):1,capture_arguments:!0,capture_return_value:!0,arg_limit_mb:1,return_limit_mb:1,enable_sampling:!1,autocapture_all_child_functions:!1,capture_sf_veritas:!1,parse_json_strings:!1}}})(t,e);if(i&&console.log(`[FuncSpan] Config for ${t}::${e}:`,c),c.enable_sampling&&c.sample_rate<1&&Math.random()>c.sample_rate)return i&&console.log(`[FuncSpan] Skipping ${e} due to sampling`),n.apply(this,a);if(c.sample_rate===0)return i&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),n.apply(this,a);i&&console.log(`[FuncSpan] Capturing function span for ${e}`);const l=v.getInstance(),g=l.getCurrentFunctionSpanId(),u=V();l.setCurrentFunctionSpanId(u);const I=process.hrtime.bigint(),m=Date.now();let p=null;c.capture_arguments&&(p={},s.paramNames.forEach((h,f)=>{f<a.length&&(p[h]=a[f])}),p&&c.arg_limit_mb>0&&(p=J(p,c.arg_limit_mb)));try{const h=n.apply(this,a);if(h&&typeof h.then=="function")return g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),h.then(A=>{const Z=process.hrtime.bigint(),ne=Date.now(),re=Number(Z-I);let Ne=null;return c.capture_return_value&&c.return_limit_mb>0&&(Ne=J(A,c.return_limit_mb)),M({functionName:e,filePath:t,metadata:s,args:p,result:Ne,error:null,duration:ne-m,durationNs:re,startTimeNs:I.toString(),async:!0,spanId:u,parentSpanId:g,pid:process.pid,threadId:w.threadId}),A},A=>{const Z=process.hrtime.bigint(),ne=Date.now(),re=Number(Z-I);throw M({functionName:e,filePath:t,metadata:s,args:p,result:null,error:A?.message||String(A),duration:ne-m,durationNs:re,startTimeNs:I.toString(),async:!0,spanId:u,parentSpanId:g,pid:process.pid,threadId:w.threadId}),A});const f=process.hrtime.bigint(),S=Date.now(),b=Number(f-I);let y=null;return c.capture_return_value&&c.return_limit_mb>0&&(y=J(h,c.return_limit_mb)),M({functionName:e,filePath:t,metadata:s,args:p,result:y,error:null,duration:S-m,durationNs:b,startTimeNs:I.toString(),async:!1,spanId:u,parentSpanId:g,pid:process.pid,threadId:w.threadId}),g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),h}catch(h){const f=process.hrtime.bigint(),S=Date.now(),b=Number(f-I);throw M({functionName:e,filePath:t,metadata:s,args:p,result:null,error:h?.message||String(h),duration:S-m,durationNs:b,startTimeNs:I.toString(),async:!1,spanId:u,parentSpanId:g,pid:process.pid,threadId:w.threadId}),g?l.setCurrentFunctionSpanId(g):l.clearCurrentFunctionSpanId(),h}};Object.defineProperty(r,"name",{value:e,writable:!1});for(const a in n)n.hasOwnProperty(a)&&(r[a]=n[a]);return r},exports.clearFuncspanOverride=Me,exports.getCurrentFunctionSpanId=j,exports.getDefaultConfig=Ct,exports.getEnvConfig=Ae,exports.getFuncspanOverride=Ce,exports.getGlobalConfig=He,exports.identify=function(n,e,t,s=!1){const r=d();new We(r.apiKey).identify(n,e,t,s)},exports.initializeConfigLoader=Te,exports.initializeWorkerPoolPatching=De,exports.isConfigLoaderInitialized=$e,exports.isWorkerPoolInitialized=Le,exports.parseHeaderOverride=Ie,exports.runWithContext=function(n){const e={...v.getInstance().getCurrentContext()};k.run(e,()=>{n()})},exports.setFuncspanOverride=xe,exports.setupInterceptors=function(n){if(!n||!n.apiKey){const r=`The required API Key is not provided: ${JSON.stringify(n)}`;console.error(r)}const{config:e}=at(n);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const r=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(r),new Error(r)}$e()||Te(void 0,e.sfDebug).catch(r=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",r)}),Le()||(De(),e.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const t=new be;t.setServiceUUID(e.serviceUUID),(function(r){function a(u,I){r.setOperationName("CollectLogs"),r.doSend([I,u])}const o=console.log.bind(console),i=console.error.bind(console),c=console.warn.bind(console),l=console.info.bind(console),g=console.debug.bind(console);console.log=(...u)=>{a("INFO",u.join(" ")),o(...u)},console.error=(...u)=>{a("ERROR",u.join(" ")),i(...u)},console.warn=(...u)=>{a("WARN",u.join(" ")),c(...u)},console.info=(...u)=>{a("INFO",u.join(" ")),l(...u)},d().logLevel==="DEBUG"&&(console.debug=(...u)=>{a("DEBUG",u.join(" ")),g(...u)})})(t),(function(r=[]){const a=new yt(r);new ft().doSend(a.getExcludedDomains());const o=new bt,i=new At;a.patchFetch(o,i),a.patchHttp(o,i)})(e.domainsToNotPropagateHeadersTo);const s=new It;s.setServiceUUID(e.serviceUUID),dt(s),ht(),new St().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 Re{constructor(e=[process.cwd()],n=!1){f(this,"rootPaths");f(this,"fileConfigs",new Map);f(this,"functionConfigs",new Map);f(this,"directoryConfigs",new Map);f(this,"hasSailfishFiles",!1);f(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)k.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(),o=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,o,l,a)}async _walkDirectory(e,n){try{const i=k.readdirSync(e,{withFileTypes:!0});for(const o of i){const s=S.join(e,o.name);o.isFile()&&o.name===".sailfish"?n.push(s):o.name==="node_modules"||o.isDirectory()&&o.name.startsWith(".")&&o.name!==".sailfish"||o.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=k.readFileSync(e,"utf-8"),i=S.dirname(e);let o=null;try{o=JSON.parse(n)}catch{try{o=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(!o)return;o.default&&this.directoryConfigs.set(i,o.default),o.files&&await this._expandFileGlobs(i,o.files,o.default||{}),o.functions&&this._storeFunctionConfigs(i,o.functions,o.default||{}),this.debug&&(console.log(`[FuncSpan ConfigLoader] Loaded config from ${e}`),console.log(`[FuncSpan ConfigLoader] Directory: ${i}`),console.log(`[FuncSpan ConfigLoader] Has default: ${!!o.default}`),console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(o.files||{}).length}`),console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(o.functions||{}).length}`))}catch(n){this.debug&&console.error(`[FuncSpan ConfigLoader] Error loading ${e}:`,n)}}async _expandFileGlobs(e,n,i){for(const[o,s]of Object.entries(n))try{const l=S.join(e,o),a=await Ae.glob(l,{absolute:!0,nodir:!0,ignore:["**/node_modules/**","**/.git/**"]});this.debug&&console.log(`[FuncSpan ConfigLoader] Pattern '${o}' 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 '${o}':`,l)}}_storeFunctionConfigs(e,n,i){for(const[o,s]of Object.entries(n)){const l=o.split("::");if(l.length!==2){this.debug&&console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${o}' (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 o=this.directoryConfigs.get(n);o&&i.unshift(o),n=S.dirname(n)}return i.reduce((o,s)=>r.mergeConfigs(o,s),{})}}let w=null;async function oe(t,e){w=new Re(t,e),await w.loadAllConfigs()}function ie(t,e){return w?w.getConfig(t,e):(process.env.SF_DEBUG==="true"&&console.log("[FuncSpan ConfigLoader] Config loader not initialized, using env config for worker process"),r.getEnvConfig())}function re(){return w!==null}const Xe=["readFile","writeFile","appendFile","readdir","stat","lstat","fstat","access","open","close","read","write","chmod","mkdir","rmdir","unlink","rename"],se=["lookup","resolve","resolve4","resolve6","resolveAny","resolveMx","resolveNs","resolveTxt","reverse"],Je=["pbkdf2","randomBytes","scrypt","generateKeyPair"],Ke=["gzip","gunzip","deflate","inflate","deflateRaw","inflateRaw","brotliCompress","brotliDecompress"];let ae=!1;function _e(t){if(typeof t!="string")return!1;const e=process.env.SF_FUNCSPAN_JSONL_FILE;if(e&&t.includes(e))return!0;const n=process.env.SF_WORKER_POOL_JSONL_FILE;return!(!n||!t.includes(n))}let ce=!1;function ge(t){if(typeof t!="string")return!1;if(t==="localhost"||t==="127.0.0.1"||t==="::1")return!0;try{const e=process.env.API_GRAPHQL_ENDPOINT;if(e&&t===new URL(e).hostname)return!0}catch{}return!1}function ke(){if(!ce)try{let t;if(typeof require>"u")return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));try{t=require("node:dns")}catch(e){return void(process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] Failed to require dns module:",e))}if(t.__sf_worker_pool_patched__)return;Object.defineProperty(t,"__sf_worker_pool_patched__",{value:!0,enumerable:!1,writable:!1,configurable:!1});for(const e of se)if(typeof t[e]=="function"){const n=t[e];t[e]=function(...i){return ge(i[0])?n.apply(this,i):typeof i[i.length-1]=="function"?r.captureWorkerPoolOperation("dns",e,n,i,this):n.apply(this,i)},Object.defineProperty(t[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 se)if(typeof e.promises[n]=="function"){const i=e.promises[n];e.promises[n]=function(...o){return ge(o[0])?i.apply(this,o):r.captureWorkerPoolPromiseOperation("dns",n,i,o,this)},Object.defineProperty(e.promises[n],"name",{value:n,writable:!1})}process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns.promises module patched successfully")}})(t),ce=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] dns module patched successfully")}catch(t){console.error("[WorkerPool] Error patching dns module:",t)}}let le=!1,de=!1,P=!1;function Ie(){if(P)return;const t=process.env.SF_DEBUG==="true";t&&console.log("[WorkerPool] Initializing worker pool patching..."),r.isModuleTrackingEnabled("fs")&&(t&&console.log("[WorkerPool] Patching fs module..."),(function(){if(!ae)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 Xe)if(typeof e[n]=="function"){const i=e[n];e[n]=function(...o){return _e(o[0])?i.apply(this,o):typeof o[o.length-1]=="function"?r.captureWorkerPoolOperation("fs",n,i,o,this):i.apply(this,o)},Object.defineProperty(e[n],"name",{value:n,writable:!1})}ae=!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")&&(t&&console.log("[WorkerPool] Patching dns module..."),ke()),r.isModuleTrackingEnabled("crypto")&&(t&&console.log("[WorkerPool] Patching crypto module..."),(function(){if(!le)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 Je)if(typeof e[n]=="function"){const i=e[n];e[n]=function(...o){return typeof o[o.length-1]=="function"?r.captureWorkerPoolOperation("crypto",n,i,o,this):i.apply(this,o)},Object.defineProperty(e[n],"name",{value:n,writable:!1})}le=!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")&&(t&&console.log("[WorkerPool] Patching zlib module..."),(function(){if(!de)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 Ke)if(typeof e[n]=="function"){const i=e[n];e[n]=function(...o){return typeof o[o.length-1]=="function"?r.captureWorkerPoolOperation("zlib",n,i,o,this):i.apply(this,o)},Object.defineProperty(e[n],"name",{value:n,writable:!1})}de=!0,process.env.SF_DEBUG==="true"&&console.log("[WorkerPool] zlib module patched successfully")}catch(e){console.error("[WorkerPool] Error patching zlib module:",e)}})()),P=!0,t&&console.log("[WorkerPool] Worker pool patching initialized")}function ue(){return P}let L=!1,$=!1,D=null;function H(t){const e=r.getGlobalConfigUnsafe(),n=e?.sfDebug||!1;n&&console.log("[FuncSpan] captureSpanData called for:",{function:t.functionName,file:t.filePath,duration:`${t.duration}ms`,async:t.async,error:t.error,spanId:t.spanId});const i={functionName:t.functionName,filePath:t.filePath,metadata:t.metadata,args:t.args,result:t.result,error:t.error,duration:t.duration,durationNs:t.durationNs,async:t.async,spanId:t.spanId,parentSpanId:t.parentSpanId};process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
146
+ 📊 Function Span:`,{function:`${t.functionName} (${t.filePath}:${t.metadata.line}:${t.metadata.column})`,duration:`${t.duration.toFixed(2)}ms`,arguments:t.args,result:t.error?`Error: ${t.error}`:t.result,spanId:t.spanId,parentSpanId:t.parentSpanId||"none"});const o=process.env.SF_FUNCSPAN_JSONL_FILE;if(o)try{const s=o==="true"||o==="1"?"funcspans.jsonl":o,l=Date.now(),a=process.hrtime.bigint(),g=BigInt(t.startTimeNs),c=Number(a-g)/1e6,d=new Date(l-c).toISOString(),I=JSON.stringify({timestamp:d,functionName:t.functionName,filePath:t.filePath,line:t.metadata.line,column:t.metadata.column,duration:t.duration,durationNs:t.durationNs,startTimeNs:t.startTimeNs,arguments:t.args,returnValue:t.error?{error:String(t.error)}:t.result,spanId:t.spanId,parentSpanId:t.parentSpanId,async:t.async,pid:t.pid,threadId:t.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{(D||(D=new r.FunctionSpanTransmitter),D).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=O.transformFunctionSpans,exports.addOrUpdateMetadata=function(t,e={},n,i=!1){const o=r.getConfig();new M(o.apiKey).addOrUpdateMetadata(t,e,n,i)},exports.captureFunctionSpan=function(t,e,n,i){const o=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 ie(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`),t.apply(this,s);if(g.sample_rate===0)return a&&console.log(`[FuncSpan] Skipping ${e} - sample_rate is 0.0`),t.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 C=process.hrtime.bigint(),p=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=t.apply(this,s);if(m&&typeof m.then=="function")return d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),m.then(A=>{const v=process.hrtime.bigint(),J=Date.now(),K=Number(v-C);let j=null;return g.capture_return_value&&g.return_limit_mb>0&&(j=r.truncateToLimit(A,g.return_limit_mb)),H({functionName:e,filePath:n,metadata:i,args:u,result:j,error:null,duration:J-p,durationNs:K,startTimeNs:C.toString(),async:!0,spanId:I,parentSpanId:d,pid:process.pid,threadId:N.threadId}),A},A=>{const v=process.hrtime.bigint(),J=Date.now(),K=Number(v-C);throw H({functionName:e,filePath:n,metadata:i,args:u,result:null,error:A?.message||String(A),duration:J-p,durationNs:K,startTimeNs:C.toString(),async:!0,spanId:I,parentSpanId:d,pid:process.pid,threadId:N.threadId}),A});const h=process.hrtime.bigint(),Z=Date.now(),b=Number(h-C);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-p,durationNs:b,startTimeNs:C.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-C);throw H({functionName:e,filePath:n,metadata:i,args:u,result:null,error:m?.message||String(m),duration:Z-p,durationNs:b,startTimeNs:C.toString(),async:!1,spanId:I,parentSpanId:d,pid:process.pid,threadId:N.threadId}),d?c.setCurrentFunctionSpanId(d):c.clearCurrentFunctionSpanId(),m}};Object.defineProperty(o,"name",{value:e,writable:!1});for(const s in t)t.hasOwnProperty(s)&&(o[s]=t[s]);return o},exports.getGlobalConfig=ie,exports.identify=function(t,e,n,i=!1){const o=r.getConfig();new M(o.apiKey).identify(t,e,n,i)},exports.initializeConfigLoader=oe,exports.initializeWorkerPoolPatching=Ie,exports.isConfigLoaderInitialized=re,exports.isSetupInterceptorsInitialized=function(){return L},exports.isWorkerPoolInitialized=ue,exports.setupInterceptors=function(t){if($)console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");else if(!L){$=!0;try{if(!t||!t.apiKey){const o=`The required API Key is not provided: ${JSON.stringify(t)}`;console.error(o)}const{config:e}=r.getOrCreateConfig(t);if(e.sfDebug&&console.log("Updated configuration after applying options:",e),!e.apiKey||!e.apiGraphqlEndpoint){const o=`The required config is not provided: ${JSON.stringify(e)}`;throw console.error(o),new Error(o)}re()||oe(void 0,e.sfDebug).catch(o=>{e.sfDebug&&console.error("[FuncSpan] Failed to initialize config loader:",o)}),process.env.SF_WORKER_POOL_DISABLED==="true"?e.sfDebug&&console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)"):ue()||(Ie(),e.sfDebug&&console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));const n=new x;n.setServiceUUID(e.serviceUUID),(function(o){function s(I,C){o.setOperationName("CollectLogs"),o.doSend([C,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(o=[]){const s=new He(o);new Fe().doSend(s.getExcludedDomains());const l=new we,a=new Ve;s.patchFetch(l,a),s.patchHttp(l,a)})(e.domainsToNotPropagateHeadersTo);const i=new ve;i.setServiceUUID(e.serviceUUID),Se(i),Ne(),new Ye().send(),L=!0,e.sfDebug&&console.log("[setupInterceptors] ✅ Initialization complete")}finally{$=!1}}};