@zharp/cloudflare 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,9 @@
1
+ import {createContextKey,ROOT_CONTEXT,SpanStatusCode,SpanKind,trace,TraceFlags,context,propagation}from'@opentelemetry/api';import {AsyncLocalStorage}from'node:async_hooks';var Et="zharp.debug_ids",J=new Map,Pe=new Set;function At(){let e=typeof globalThis<"u"?globalThis:void 0,t=e&&e.__zharpDebugIds;return t&&typeof t=="object"?t:void 0}function $e(e){let t=e.trim();if(!t)return;let n=/^at (?:async )?(?:.*? \()?(.+?):\d+:\d+\)?$/.exec(t);if(n)return Le(n[1]);if(!t.startsWith("at "))return n=/^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(t),n?Le(n[1]):void 0}function Le(e){let t=e.replace(/^address at /,"");if(!(!t||t.includes("eval at ")||t==="<anonymous>"||t==="native"))return t}function Tt(e){let t=[];for(let n of e.split(`
2
+ `)){let r=$e(n);r&&!t.includes(r)&&t.push(r);}return t}function Ct(){let e=At();if(e)for(let t in e){if(Pe.has(t))continue;Pe.add(t);let n=e[t];if(typeof n=="string")for(let r of t.split(`
3
+ `)){let o=$e(r);if(o){J.set(o,n);break}}}}function qt(e){if(e)try{if(Ct(),J.size===0)return;let t;for(let n of Tt(e)){let r=J.get(n);r&&((t??={})[n]=r);}return t}catch{return}}function V(e){let t=qt(e);return t?{[Et]:JSON.stringify(t)}:{}}function ee(e){let t=new Uint8Array(e),n=typeof crypto<"u"?crypto:void 0;if(n&&n.getRandomValues)n.getRandomValues(t);else for(let o=0;o<e;o++)t[o]=Math.random()*256|0;let r="";for(let o=0;o<e;o++)r+=(t[o]<16?"0":"")+t[o].toString(16);return /^0+$/.test(r)?ee(e):r}var je=()=>ee(16),He=()=>ee(8);function q(){let e=typeof performance<"u"?performance:void 0;return e&&e.timeOrigin?e.timeOrigin+e.now():Date.now()}function P(e){let t=Math.floor(e),n=Math.round((e-t)*1e6);return n>=1e6?`${t+1}000000`:`${t}${String(n).padStart(6,"0")}`}function Ue(e,t=0){return typeof e=="string"?{stringValue:e}:typeof e=="boolean"?{boolValue:e}:typeof e=="number"?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:e instanceof Error?{stringValue:`${e.name}: ${e.message}`}:e==null?{stringValue:""}:t<4&&Array.isArray(e)?{arrayValue:{values:e.map(n=>Ue(n,t+1))}}:t<4&&typeof e=="object"?{kvlistValue:{values:O(e,t+1)}}:{stringValue:L(e)}}function O(e,t=0){let n=[];for(let r in e){let o=e[r];o!==void 0&&n.push({key:r,value:Ue(o,t)});}return n}function L(e){if(typeof e=="string")return e;if(e instanceof Error)return `${e.name}: ${e.message}`;try{let t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}function l(e){try{return e()}catch{return}}function K(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).length:e.length*2}function W(e){if(e instanceof Error)return e;if(e&&typeof e=="object"&&typeof e.message=="string"){let t=new Error(e.message);return t.name=typeof e.name=="string"?e.name:"Error",typeof e.stack=="string"&&(t.stack=e.stack),t}return new Error(typeof e=="string"?e:`Non-Error thrown: ${L(e)}`)}function te(e,t){let n=(e.name&&e.name!=="Error"?e.name:e.constructor?.name)||"Error",r=e.message||"",o=`${n}: ${r}`,s=typeof e.stack=="string"?e.stack:"";return s.startsWith(e.name||n)||(s=s?`${o}
4
+ ${s}`:o),{"exception.type":n,"exception.message":r,"exception.stacktrace":s,"zharp.handled":t?"true":"false",...V(s)}}var Ot={debug:"debug",log:"info",info:"info",warn:"warn",error:"error"};function Fe(e,t){let n={},r=false;for(let o of e){let s=console[o];if(typeof s!="function"||s.__zharp)continue;n[o]=s;let i=function(...a){s.apply(this??console,a),!r&&(r=true,l(()=>{let u=a.map(c=>c instanceof Error?c.stack||String(c):L(c)).join(" ");u.startsWith("[Zharp]")||t(Ot[o],u);}),r=false);};i.__zharp=true,console[o]=i;}return ()=>Object.assign(console,n)}var re="[Filtered]";var _t=["password","passwd","passphrase","secret","token","apikey","accesskey","privatekey","authorization","cookie","creditcard","cardnumber","cvv","cvc","ssn","iban","sessionid","signature","credential"],It=["auth","pin","pwd","otp","card","pan","jwt","sid","codeverifier"],Pt=["key","sig","code","state","session"],ne=e=>e.toLowerCase().replace(/[^a-z0-9]/g,"");function se(e,t=[]){let n=ne(e);return n?It.includes(n)||_t.some(r=>n.includes(r))?true:t.some(r=>r instanceof RegExp?r.test(e):ne(r)===n):false}function F(e,t=[]){if(!e)return e;let n=e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i,"$1"),r=n.indexOf("?");if(r<0)return n;let o=n.indexOf("#",r),s=n.slice(r+1,o<0?void 0:o),i=Lt(s,t);return i!==s&&(n=n.slice(0,r+1)+i+(o<0?"":n.slice(o))),n}function Lt(e,t=[]){return e&&e.split("&").map(n=>{let r=n.indexOf("=");if(r<0)return n;let o=n.slice(0,r);try{o=decodeURIComponent(o.replace(/\+/g," "));}catch{}return (se(o,t)||Pt.includes(ne(o)))&&r<n.length-1?`${n.slice(0,r)}=${re}`:n}).join("&")}var $t=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-csrf-token","x-xsrf-token"]),jt=40,ve=512;function Ne(e,t){return e===false||t==="false"||t==="0"?null:{redact:typeof e=="object"&&e?.redact?e.redact:[]}}function Ht(e,t,n){if(t==null)return null;if($t.has(e)||se(e,n.redact))return re;let r=Array.isArray(t)?t.join(", "):String(t);return r.length>ve?`${r.slice(0,ve)}\u2026`:r}function _(e,t,n){let r={};if(!t)return r;let o=typeof t[Symbol.iterator]=="function"?[...t]:Object.entries(t),s=0;for(let[i,a]of o){if(s>=jt)break;let u=i.toLowerCase(),c=Ht(u,a,n);c!==null&&(r[`http.${e}.header.${u}`]=c,s++);}return r}var Ut=100,oe=5e3,ie=1e3,Ft=5*6e4,vt=1e6,Me=6e4,ae=false;async function ce(e,t,n,r=false){if(ae)return 401;let o={"Content-Type":"application/json",Authorization:`Bearer ${e.key}`},s=n;if(!r&&e.compress!==false&&n.length>2048&&typeof CompressionStream<"u")try{s=await new Response(new Blob([n]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer(),o["Content-Encoding"]="gzip";}catch{s=n;}try{let i=await e.fetch.call(globalThis,`${e.url}/v1/${t}`,{method:"POST",headers:o,body:s,keepalive:r,credentials:"omit"});return (i.status===401||i.status===403)&&(ae||(ae=!0,console.warn(`[Zharp] The key was rejected (HTTP ${i.status}); ${e.rejectedHint??"nothing more will be sent from this page. Check Zharp.init({ key }) and the app's allowed origins."}`))),i.status}catch{return 0}}var ue=0;function Nt(e,t,n){let r=K(n);ue+r<=Me?(ue+=r,ce(e,t,n,true).finally(()=>{ue-=r;})):ce(e,t,n);}var Bt=e=>e===0||e===429||e>=500;function Be(e,t,n){let r=K(JSON.stringify(n([]))),o=[],s=[],i=r;for(let a of e){let u=K(JSON.stringify(a))+1;s.length&&i+u>t&&(o.push({body:JSON.stringify(n(s)),items:s}),s=[],i=r),s.push(a),i+=u;}return s.length&&o.push({body:JSON.stringify(n(s)),items:s}),o}var v=class{constructor(t,n,r,o=true){this.endpoint=t;this.signal=n;this.wrap=r;this.timers=o;}endpoint;signal;wrap;timers;queue=[];timer=null;sending=null;failures=0;add(t){this.queue.push(t),this.queue.length>ie&&this.queue.splice(0,this.queue.length-ie),this.queue.length>=Ut&&!this.failures?this.flush():this.schedule(oe);}async flush(){for(;this.sending;)await this.sending;if(this.queue.length)return this.sending=this.send().finally(()=>this.sending=null),this.sending}flushOnHide(){if(!this.queue.length)return;let t=this.queue;this.queue=[];for(let{body:n}of Be(t,Me,this.wrap))Nt(this.endpoint,this.signal,n);}schedule(t){this.timer||!this.timers||(this.timer=setTimeout(()=>{this.timer=null,this.flush();},t));}async send(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=this.queue;this.queue=[];let n=Be(t,vt,this.wrap);for(let r=0;r<n.length;r++){let o=await ce(this.endpoint,this.signal,n[r].body);if(Bt(o)){let s=n.slice(r).flatMap(i=>i.items);this.queue=s.concat(this.queue).slice(-ie),this.failures++,this.schedule(Math.min(oe*2**this.failures,Ft));return}this.failures=0;}this.queue.length&&this.schedule(oe);}};var N="0.1.0";var Ze="https://api.zharp.io/api/v1/otlp",m=e=>typeof e=="string"&&e.trim()?e.trim():void 0,Q=e=>{if(typeof e=="boolean")return e;let t=m(e)?.toLowerCase();if(t){if(/^(true|1|yes|on)$/.test(t))return true;if(/^(false|0|no|off)$/.test(t))return false}};function Mt(e){let t=e.CF_VERSION_METADATA;return t&&typeof t=="object"?{id:m(t.id),tag:m(t.tag)}:{}}function De(e,t,n){let r=e&&typeof e=="object"?e:{},o=(typeof t=="function"?t(r):t)??{};if(Q(r.ZHARP_DISABLED))return null;let s=m(o.key)??m(r.ZHARP_KEY)??m(r.ZHARP_API_KEY);if(!s)return null;let i=Mt(r),a=m(o.release)??m(r.ZHARP_RELEASE)??i.id,u=typeof o.sampleRate=="number"?o.sampleRate:Number(m(r.ZHARP_SAMPLE_RATE)??1),c=Q(r.ZHARP_CAPTURE_HEADERS);return {key:s,endpoint:(m(o.endpoint)??m(r.ZHARP_ENDPOINT)??Ze).replace(/\/+$/,""),sampleRate:Number.isFinite(u)?Math.min(1,Math.max(0,u)):1,tracing:o.tracing??Q(r.ZHARP_TRACING)??true,logs:o.logs??Q(r.ZHARP_LOGS)??false,captureHeaders:o.captureHeaders??(c===false?false:void 0),captureQueryErrors:o.captureQueryErrors??true,ignoreUrls:o.ignoreUrls??[],resource:{"service.name":m(o.service)??m(r.ZHARP_SERVICE)??n.service,"service.version":a,"deployment.environment.name":m(o.environment)??m(r.ZHARP_ENVIRONMENT)??m(r.ZHARP_ENV),"telemetry.sdk.name":"zharp","telemetry.sdk.language":"webjs","telemetry.sdk.version":N,"cloud.provider":"cloudflare","cloud.platform":n.platform,"faas.version":i.id,"cloudflare.version.tag":i.tag}}}var fe=class{als=new AsyncLocalStorage;active(){return this.als.getStore()??ROOT_CONTEXT}with(t,n,r,...o){return this.als.run(t,()=>n.apply(r,o))}bind(t,n){if(typeof n!="function")return n;let r=this;return function(...o){return r.with(t,()=>n.apply(this,o))}}enable(){return this}disable(){return this}},j=new fe,Ve=createContextKey("zharp.cloudflare.request"),b=()=>j.active(),R=(e=b())=>e.getValue(Ve),Ke=(e,t)=>e.setValue(Ve,t),I=()=>{let e=trace.getSpan(b());return e instanceof $?e:void 0},le=null,We=e=>{le=e;},Wt=e=>e+1,Qt=64,$=class{constructor(t,n,r,o,s,i,a){this.name=t;this.kind=n;let u=r&&trace.isSpanContextValid(r);this.traceId=u?r.traceId:je(),this.parentSpanId=u?r.spanId:void 0,this.sampled=u?(r.traceFlags&TraceFlags.SAMPLED)===TraceFlags.SAMPLED:Math.random()<(le?.sampleRate??1),this.startTime=i!==void 0?de(i):q(),this.request=o,s&&Object.assign(this.attributes,s),a&&this.links.push(...a);}name;kind;traceId;spanId=He();parentSpanId;sampled;attributes={};startTime;request;events=[];links=[];status={code:SpanStatusCode.UNSET};endTime=0;get ended(){return this.endTime!==0}spanContext(){return {traceId:this.traceId,spanId:this.spanId,traceFlags:this.sampled?TraceFlags.SAMPLED:TraceFlags.NONE}}setAttribute(t,n){return !this.endTime&&n!==void 0&&(this.attributes[t]=n),this}setAttributes(t){for(let n in t)this.setAttribute(n,t[n]);return this}addEvent(t,n,r){if(this.endTime||this.events.length>=Qt)return this;if(t==="exception")return this;let o=typeof n=="number"||n instanceof Date||Array.isArray(n);return this.events.push({name:t,time:de(o?n:r??q()),attributes:o?void 0:n}),this}addLink(t){return this.links.push(t),this}addLinks(t){return this.links.push(...t),this}setStatus(t){return this.endTime||(this.status=t),this}updateName(t){return this.endTime||(this.name=t),this}isRecording(){return !this.endTime}recordException(t){Qe?.(t,this);}end(t){this.endTime||(this.endTime=Math.max(t!==void 0?de(t):q(),this.startTime),this.sampled&&le?.export(this));}toOtlp(t){return {traceId:this.traceId,spanId:this.spanId,parentSpanId:this.parentSpanId,name:this.name,kind:Wt(this.kind),startTimeUnixNano:P(this.startTime),endTimeUnixNano:P(this.endTime),attributes:O({...t,...this.attributes}),events:this.events.length?this.events.map(n=>({name:n.name,timeUnixNano:P(n.time),attributes:O(n.attributes??{})})):void 0,links:this.links.length?this.links.map(n=>({traceId:n.context.traceId,spanId:n.context.spanId,attributes:O(n.attributes??{})})):void 0,status:this.status.message?{code:this.status.code,message:this.status.message}:{code:this.status.code}}}},Qe=null,Xe=e=>{Qe=e;};function de(e){return typeof e=="number"?e<1e12?typeof performance<"u"&&performance.timeOrigin?performance.timeOrigin+e:Date.now():e:e instanceof Date?e.getTime():Array.isArray(e)?e[0]*1e3+e[1]/1e6:q()}function k(e,t={},n=b()){let r=t.root?void 0:trace.getSpanContext(n);return new $(e,t.kind??SpanKind.INTERNAL,r,R(n),t.attributes,t.startTime,t.links)}function X(e,t,n=b()){return j.with(trace.setSpan(n,e),t)}var pe=class{startSpan(t,n,r){return k(t,n,r??b())}startActiveSpan(t,...n){let r=n[n.length-1],o=n.length>1?n[0]:void 0,i=(n.length>2?n[1]:void 0)??b(),a=k(t,o,i);return j.with(trace.setSpan(i,a),()=>r(a))}},Xt=new pe,Yt={getTracer:()=>Xt},Gt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function ge(e){let t=e?Gt.exec(e.trim().toLowerCase()):null;if(!(!t||/^0+$/.test(t[1])||/^0+$/.test(t[2])))return {traceId:t[1],spanId:t[2],traceFlags:parseInt(t[3],16)&1,isRemote:true}}function he(e){return `00-${e.traceId}-${e.spanId}-${e.traceFlags&TraceFlags.SAMPLED?"01":"00"}`}var Jt={inject(e,t,n){let r=trace.getSpanContext(e);r&&trace.isSpanContextValid(r)&&n.set(t,"traceparent",he(r));},extract(e,t,n){let r=n.get(t,"traceparent"),o=ge(Array.isArray(r)?r[0]:r);return o?trace.setSpanContext(e,o):e},fields:()=>["traceparent"]},ze=false;function Ye(){if(!ze){ze=true;try{context.setGlobalContextManager(j),trace.setGlobalTracerProvider(Yt),propagation.setGlobalPropagator(Jt);}catch{}}}var me=new WeakMap;function Ge(e){let t=e&&typeof e=="object"?me.get(e):void 0;return t&&(t.claimed=true),t}function Je(e){return e.queryFailures.filter(t=>!t.claimed)}function ye(e){let t={},n=Error.stackTraceLimit;try{Error.stackTraceLimit=40,Error.captureStackTrace?.(t,e);}finally{Error.stackTraceLimit=n;}return (t.stack??"").split(`
5
+ `).slice(1).filter(r=>/^\s+at /.test(r))}function et(e){return /\b(SQLITE_[A-Z_]+)\b/.exec(e)?.[1]}var tt=e=>/^\s*(\w+)/.exec(e)?.[1]?.toUpperCase()??"QUERY",be=4e3;function en(e,t,n,r,o){let s=e?.message??String(e),i=et(s),a="D1Error",u={"zharp.mechanism":"db","db.system":"sqlite","db.statement":n.slice(0,be),"db.name":r,...i?{"db.error.code":i}:{}};return {error:e,span:t,claimed:false,attributes:u,exception(c){let f=[`${a}: ${s}`,...o].join(`
6
+ `);return {"exception.type":a,"exception.message":s,"exception.stacktrace":f,"zharp.handled":c?"true":"false",...V(f)}}}}async function we(e,t){let n=b(),r=R(n);if(!r)return t();let o=k(`${e.operation} ${e.database}`,{kind:SpanKind.CLIENT,attributes:{"db.system":"sqlite","db.system.name":"sqlite","db.namespace":e.database,"db.operation.name":e.operation,"db.statement":e.sql.slice(0,be),"db.query.text":e.sql.slice(0,be),"cloudflare.binding.type":"d1"}},n);try{let s=await t();return l(()=>{let i=s?.meta??(Array.isArray(s)?s[0]?.meta:void 0);i&&o.setAttributes({"cloudflare.d1.rows_read":i.rows_read,"cloudflare.d1.rows_written":i.rows_written,"cloudflare.d1.served_by":i.served_by});let a=s?.results;Array.isArray(a)&&o.setAttribute("db.response.returned_rows",a.length);}),s}catch(s){let i=s?.message??String(s);o.setStatus({code:SpanStatusCode.ERROR,message:i});let a=et(i);if(a&&o.setAttribute("db.response.status_code",a),e.captureErrors&&s&&typeof s=="object"&&!me.has(s)){let u=en(s,o,e.sql,e.database,e.frames);me.set(s,u),r.queryFailures.push(u);}throw s}finally{o.end();}}var nt=new WeakMap,rt=new WeakMap,tn=new Set(["first","all","run","raw"]);function st(e,t,n,r){let o=new Proxy(e,{get(s,i){let a=Reflect.get(s,i,s);if(typeof a!="function")return a;if(i==="bind")return (...u)=>st(a.apply(s,u),t,n,r);if(typeof i=="string"&&tn.has(i)){let u=function(...c){let f=ye(u);return we({database:n,sql:t,operation:tt(t),frames:f,captureErrors:r},()=>a.apply(s,c))};return u}return a.bind(s)}});return nt.set(o,e),rt.set(o,t),o}function Re(e,t,n){return new Proxy(e,{get(r,o){let s=Reflect.get(r,o,r);if(typeof s!="function")return s;if(o==="prepare")return i=>st(s.call(r,i),String(i??""),t,n);if(o==="batch"){let i=function(a){let u=ye(i),c=Array.isArray(a)?a:[],f=c.map(d=>(d&&typeof d=="object"?rt.get(d):void 0)??"?").join(`;
7
+ `),p=c.map(d=>d&&typeof d=="object"?nt.get(d)??d:d);return we({database:t,sql:f,operation:"BATCH",frames:u,captureErrors:n},()=>s.call(r,p))};return i}if(o==="exec"){let i=function(a){let u=ye(i);return we({database:t,sql:String(a??""),operation:tt(String(a??"")),frames:u,captureErrors:n},()=>s.call(r,a))};return i}return o==="withSession"?(...i)=>Re(s.apply(r,i),t,n):s.bind(r)}})}var nn=()=>typeof location<"u"?location.href:"http://localhost/";function ot(e,t){let n=l(()=>new URL(e,nn()));return n?t.some(r=>r instanceof RegExp?r.test(n.href):r?r.includes("://")?n.href.startsWith(r):n.host===r||n.hostname===r:false):false}var it=false;function at(e){if(it||typeof globalThis.fetch!="function")return;it=true;let t=globalThis.fetch,n=function(o,s){return Se(e,t,globalThis,o,s,void 0)};n.__zharp=true,globalThis.fetch=n;}function Se(e,t,n,r,o,s){let i=b();if(!R(i)||!e.settings.tracing)return t.call(n,r,o);let a;try{a=new Request(r,o);}catch{return t.call(n,r,o)}let u=l(()=>new URL(a.url));if(!s&&(!u||a.url.startsWith(e.settings.endpoint)||ot(a.url,e.settings.ignoreUrls)))return t.call(n,a);let c=a.method.toUpperCase(),f=k(s?`${c} ${s.name}`:`${c} ${u?.host??""}`.trim(),{kind:SpanKind.CLIENT,attributes:{"http.request.method":c,"url.full":F(a.url),"server.address":s?void 0:u?.hostname,"server.port":s||!u?.port?void 0:Number(u.port),...s?{"cloudflare.binding.name":s.name,"cloudflare.binding.type":s.type}:{}}},i);return a.headers.has("traceparent")||l(()=>a.headers.set("traceparent",he(f.spanContext()))),e.headers&&f.setAttributes(_("request",a.headers,e.headers)),X(f,()=>t.call(n,a),i).then(p=>(l(()=>{f.setAttribute("http.response.status_code",p.status),e.headers&&f.setAttributes(_("response",p.headers,e.headers)),p.status>=400&&f.setStatus({code:SpanStatusCode.ERROR,message:`HTTP ${p.status}`}),f.end();}),p),p=>{throw l(()=>{f.setStatus({code:SpanStatusCode.ERROR,message:p?.message??String(p)}),f.setAttribute("error.type",p?.name||"Error"),f.end();}),p})}var rn={trace:1,debug:5,info:9,warn:13,error:17,fatal:21},ft={},lt=null,xe=class{constructor(t){this.settings=t;let n=globalThis.fetch;this.endpoint={url:t.endpoint,key:t.key,fetch:n,rejectedHint:"nothing more will be sent from this isolate. Check the ZHARP_KEY secret (the app key from the Zharp dashboard)."},this.headers=Ne(t.captureHeaders);let r=O(t.resource),o={name:"@zharp/cloudflare",version:N};this.spans=new v(this.endpoint,"traces",s=>({resourceSpans:[{resource:{attributes:r},scopeSpans:[{scope:o,spans:s}]}]}),false),this.logs=new v(this.endpoint,"logs",s=>({resourceLogs:[{resource:{attributes:r},scopeLogs:[{scope:o,logRecords:s}]}]}),false),We({sampleRate:t.sampleRate,export:s=>{t.tracing&&this.spans.add(s.toOtlp(ut(s.request)));}}),Xe((s,i)=>this.report(s,true,{"zharp.mechanism":"opentelemetry"},i)),Ye(),t.tracing&&at(this),t.logs&&Fe(["debug","log","info","warn","error"],(s,i)=>this.emit(s,i,{"log.source":"console"}));}settings;endpoint;spans;logs;headers;reported=new WeakSet;newRequest(){return {runtime:this,tags:{},user:null,queryFailures:[],pending:[]}}report(t,n,r={},o=I()){l(()=>{if(t&&typeof t=="object"){if(this.reported.has(t))return;this.reported.add(t);}let s=Ge(t),i=s?s.exception(n):te(W(t),n);this.emit("error",`${i["exception.type"]}: ${i["exception.message"]}`,{...s?.attributes??{},...r},i,o);});}wasReported(t){return !!t&&typeof t=="object"&&this.reported.has(t)}emit(t,n,r,o,s=I()){l(()=>{let i=P(q()),a=s?.request??R(),u={...ut(a)};for(let c in r){let f=r[c];f instanceof Error&&!o&&(t==="error"||t==="fatal")?(o=te(f,!0),this.reported.add(f)):u[c]=f;}this.logs.add({timeUnixNano:i,observedTimeUnixNano:i,severityNumber:rn[t],severityText:t.toUpperCase(),body:{stringValue:typeof n=="string"?n:n instanceof Error?n.message:L(n)},attributes:O({...u,...o}),traceId:s?.traceId,spanId:s?.spanId});});}async finish(t){try{for(let n=0;n<t.pending.length;){let r=t.pending.slice(n);n=t.pending.length,await Promise.allSettled(r);}for(let n of Je(t))this.report(n.error,!0,{},n.span);}catch{}await this.flush();}async flush(){await Promise.all([this.spans.flush(),this.logs.flush()]).catch(()=>{});}};function ut(e){let t=e?.user??lt;return {...ft,...e?.tags,"enduser.id":t?String(t.id):void 0,"enduser.email":t?.email,"enduser.name":t?.name}}function pt(e,t){let n=R()?.tags??ft;t==null?delete n[e]:n[e]=t;}function gt(e){let t=e&&e.id!==void 0&&e.id!==null&&e.id!==""?{id:e.id,email:e.email,name:e.name}:null,n=R();n?n.user=t:lt=t;}var M=null,ct=false,dt;function Y(e,t,n){if(M)return M;t!==void 0&&(dt=t);let r=l(()=>De(e,t??dt,n));if(!r){let o=/^(true|1|yes|on)$/i.test(String(e?.ZHARP_DISABLED??""));return !ct&&!o&&(ct=true,console.warn("[Zharp] No key: set the ZHARP_KEY secret (wrangler secret put ZHARP_KEY) to the app key from the Zharp dashboard. Nothing will be sent.")),null}return M=new xe(r),M}var Z=()=>M;var ht={D1Database:"d1",D1DatabaseSession:"d1",KvNamespace:"kv",R2Bucket:"r2",WorkerQueue:"queue",Fetcher:"service",DurableObjectNamespace:"durable-object"},D=(e,...t)=>t.every(n=>typeof l(()=>e[n])=="function");function sn(e){if(!e||typeof e!="object")return;let t=l(()=>Object.getPrototypeOf(e)?.constructor?.name);if(t&&ht[t])return ht[t];if(!(t&&t!=="Object")){if(D(e,"prepare","batch","exec"))return "d1";if(D(e,"head","get","put","list","delete","createMultipartUpload"))return "r2";if(D(e,"get","put","list","delete","getWithMetadata"))return "kv";if(D(e,"send","sendBatch"))return "queue";if(D(e,"idFromName","get"))return "durable-object"}}var G=Symbol.for("zharp.cloudflare.wrapped"),mt=new WeakMap;function Ee(e,t){return !e||typeof e!="object"||e[G]?e:new Proxy(e,{get(n,r,o){if(r===G)return true;let s=Reflect.get(n,r,o);return typeof r!="string"?s:Ae(s,r,t)??s}})}function Ae(e,t,n){if(!e||typeof e!="object"||e[G])return;let r=sn(e);if(!r)return;let o=mt.get(e);o||mt.set(e,o=new Map);let s=o.get(t);if(s)return s;let i=an(on(r,e,t,n));return o.set(t,i),i}function on(e,t,n,r){switch(e){case "d1":return Re(t,n,r.settings.captureQueryErrors);case "kv":return ke(t,["get","getWithMetadata","put","list","delete"],(o,s)=>({name:`KV ${o} ${n}`,kind:SpanKind.CLIENT,attributes:{"db.system":"cloudflare_kv","db.namespace":n,"db.operation.name":o,"cloudflare.binding.type":"kv","cloudflare.kv.key":typeof s[0]=="string"?s[0]:void 0,"cloudflare.kv.keys":Array.isArray(s[0])?s[0].length:void 0},result:o.startsWith("get")?i=>({"cloudflare.kv.hit":o==="get"?i!==null:i?.value!==null}):void 0}));case "r2":return ke(t,["head","get","put","list","delete","createMultipartUpload","resumeMultipartUpload"],(o,s)=>({name:`R2 ${o} ${n}`,kind:SpanKind.CLIENT,attributes:{"cloudflare.binding.type":"r2","cloudflare.r2.bucket":n,"cloudflare.r2.operation":o,"cloudflare.r2.key":typeof s[0]=="string"?s[0]:void 0},result:o==="get"||o==="head"?i=>({"cloudflare.r2.hit":i!==null}):void 0}));case "queue":return ke(t,["send","sendBatch"],(o,s)=>({name:`${n} send`,kind:SpanKind.PRODUCER,attributes:{"messaging.system":"cloudflare_queues","messaging.operation.type":"send","messaging.destination.name":n,"messaging.batch.message_count":o==="sendBatch"&&Array.isArray(s[0])?s[0].length:void 0}}));case "service":return yt(t,{name:n,type:"service"},r);case "durable-object":return new Proxy(t,{get(o,s){let i=Reflect.get(o,s,o);return typeof i!="function"?i:s==="get"||s==="getByName"?(...a)=>yt(i.apply(o,a),{name:n,type:"durable-object"},r):i.bind(o)}})}}function an(e){return new Proxy(e,{get(t,n,r){return n===G?true:Reflect.get(t,n,r)}})}function yt(e,t,n){return !e||typeof e!="object"?e:new Proxy(e,{get(r,o){let s=Reflect.get(r,o,r);return o!=="fetch"||typeof s!="function"?s:(i,a)=>Se(n,s,r,i,a,t)}})}function ke(e,t,n){let r=new Set(t);return new Proxy(e,{get(o,s){let i=Reflect.get(o,s,o);return typeof i!="function"?i:typeof s!="string"||!r.has(s)?i.bind(o):(...a)=>{let u=b();if(!R(u))return i.apply(o,a);let c=n(s,a),f=k(c.name,{kind:c.kind,attributes:c.attributes},u),p;try{p=i.apply(o,a);}catch(d){throw f.setStatus({code:SpanStatusCode.ERROR,message:d?.message}),f.end(),d}return Promise.resolve(p).then(d=>(c.result&&l(()=>f.setAttributes(c.result(d))),f.end(),d),d=>{throw f.setStatus({code:SpanStatusCode.ERROR,message:d?.message??String(d)}),f.end(),d})}}})}function Te(e){return !!e&&typeof e=="object"&&typeof e.fetch=="function"&&typeof e.router?.match=="function"&&Array.isArray(e.routes)}function wt(e,t){return l(()=>{let n=typeof e.getPath=="function"?e.getPath(t):new URL(t.url).pathname,r=t.method==="HEAD"?"GET":t.method,[o]=e.router.match(r,n)??[];if(!Array.isArray(o)||!o.length)return;let s=o.map(u=>u?.[0]?.[1]).filter(u=>u&&typeof u.path=="string"),a=([...s].reverse().find(u=>u.method!=="ALL")??s[s.length-1])?.path;return a&&a!=="/*"&&a!=="*"?a:void 0})}var bt=Symbol.for("zharp.cloudflare.honoErrorHandler");function Rt(e,t){l(()=>{let n=e.errorHandler;if(typeof n!="function"||n[bt])return;let r=function(o,s){let i=o?.status;return typeof o?.getResponse=="function"&&typeof i=="number"&&i<500||t.report(o,!1,{"zharp.mechanism":"hono"},I()),n.call(this,o,s)};r[bt]=!0,e.errorHandler=r;});}var Ce={service:"worker",platform:"cloudflare.workers"},dn={service:"pages",platform:"cloudflare.pages"},fn=/^(\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|[A-Za-z0-9_-]{24,})$/i,ln=e=>e.split("/").map(t=>fn.test(t)?":id":t).join("/")||"/";async function H(e,t,n,r,o){let s=e.newRequest(),i=ge(t.traceparent),a=new $(t.name,t.kind,i,s,t.attributes),u=trace.setSpan(Ke(ROOT_CONTEXT,s),a);try{let c=await j.with(u,()=>r(s,a));return o&&l(()=>o(c,a)),c}catch(c){throw e.report(c,false,{"zharp.mechanism":t.mechanism},a),a.setStatus({code:SpanStatusCode.ERROR,message:c?.message??String(c)}),t.attributes["http.request.method"]&&!a.attributes["http.response.status_code"]&&a.setAttribute("http.response.status_code",500),c}finally{a.end();let c=e.finish(s);n&&l(()=>n.waitUntil(c));}}function z(e,t,n){return !e||typeof e.waitUntil!="function"?e:new Proxy(e,{get(r,o){let s=Reflect.get(r,o,r);return o==="waitUntil"&&typeof s=="function"?i=>{let a=Promise.resolve(i).catch(u=>{throw n.report(u,false,{"zharp.mechanism":"waitUntil"}),u});return t.pending.push(a),s.call(r,a)}:typeof s=="function"?s.bind(r):s}})}function qe(e,t,n,r={}){let o=l(()=>new URL(e.url)),s=e.method.toUpperCase(),i=e.cf,a=e.headers;return {name:`${s} ${ln(o?.pathname??"/")}`,kind:SpanKind.SERVER,traceparent:a.get("traceparent"),mechanism:n,attributes:{"faas.trigger":"http","http.request.method":s,"url.full":F(e.url),"url.path":o?.pathname,"url.scheme":o?.protocol.replace(":",""),"server.address":o?.hostname,"user_agent.original":a.get("user-agent")??void 0,"client.address":a.get("cf-connecting-ip")??void 0,"cloudflare.ray_id":a.get("cf-ray")??void 0,"cloudflare.colo":typeof i?.colo=="string"?i.colo:void 0,"geo.country.iso_code":typeof i?.country=="string"?i.country:void 0,...t.headers?_("request",a,t.headers):{},...r}}}function Oe(e){return (t,n)=>{t instanceof Response&&(n.setAttribute("http.response.status_code",t.status),e.headers&&n.setAttributes(_("response",t.headers,e.headers)),t.status>=500&&n.setStatus({code:SpanStatusCode.ERROR,message:`HTTP ${t.status}`}));}}function pn(e,t,n,r,o){return function(...s){let i=n??this,a=e==="fetch"||e==="scheduled"||e==="queue"||e==="email"||e==="tail"||e==="trace"?s[1]:void 0,u=s[2],c=a!==void 0?Y(a,r,Ce):null;if(!c)return t.apply(i,s);let f=Ee(a,c);if(e==="fetch"){let d=s[0];Te(o)&&Rt(o,c);let C=qe(d,c,"cloudflare.fetch");return H(c,C,u,E=>t.call(i,d,f,z(u,E,c),...s.slice(3)),(E,h)=>{Oe(c)(E,h);let y=Te(o)?wt(o,d):void 0;y&&(h.setAttribute("http.route",y),h.updateName(`${d.method.toUpperCase()} ${y}`));})}if(e==="scheduled"){let d=s[0]??{},C={name:`cron ${d.cron??""}`.trim(),kind:SpanKind.SERVER,mechanism:"cloudflare.scheduled",attributes:{"faas.trigger":"timer","faas.cron":d.cron,"faas.time":typeof d.scheduledTime=="number"?new Date(d.scheduledTime).toISOString():void 0}};return H(c,C,u,E=>t.call(i,d,f,z(u,E,c)))}if(e==="queue"){let d=s[0]??{},C={name:`${d.queue??"queue"} process`,kind:SpanKind.CONSUMER,mechanism:"cloudflare.queue",attributes:{"faas.trigger":"pubsub","messaging.system":"cloudflare_queues","messaging.operation.type":"process","messaging.destination.name":d.queue,"messaging.batch.message_count":Array.isArray(d.messages)?d.messages.length:void 0}};return H(c,C,u,E=>t.call(i,d,f,z(u,E,c)))}let p={name:e,kind:SpanKind.SERVER,mechanism:`cloudflare.${e}`,attributes:{"faas.trigger":"other"}};return H(c,p,u,d=>t.call(i,s[0],f,z(u,d,c),...s.slice(3)))}}var gn=new Set(["fetch","scheduled","queue","email","tail","trace","test"]);function hn(e,t){let[n,r]=t===void 0?[void 0,e]:[e,t];if(typeof r=="function")return xt(r,n,Ce,"worker");if(!r||typeof r!="object")return r;let o=new Map;return new Proxy(r,{get(s,i,a){let u=Reflect.get(s,i,a);if(typeof i!="string"||!gn.has(i)||typeof u!="function")return u;let c=o.get(i);return c||o.set(i,c=pn(i,u,s,n,s)),c}})}var St={webSocketMessage:"websocket message",webSocketClose:"websocket close",webSocketError:"websocket error"},mn=new Set(["constructor","then","toJSON","dup","ctx","env","state","storage"]);function yn(e,t){return xt(e,t,Ce,"durable-object")}function xt(e,t,n,r){return new Proxy(e,{construct(o,s,i){let[a,u]=s,c=Y(u,t,n);if(!c)return Reflect.construct(o,s,i);let f=Reflect.construct(o,[a,Ee(u,c),...s.slice(2)],i),p=o.name||(r==="durable-object"?"DurableObject":"Worker"),d=l(()=>a?.id?.toString?.()),C=new Map,E=(h,y)=>function(...A){let S={"cloudflare.durable_object.class":r==="durable-object"?p:void 0,"cloudflare.durable_object.id":r==="durable-object"?d:void 0},x,Ie;h==="fetch"&&A[0]instanceof Request?(x=qe(A[0],c,r==="durable-object"?"cloudflare.durable_object":"cloudflare.fetch",S),Ie=Oe(c)):h==="alarm"?x={name:`${p} alarm`,kind:SpanKind.SERVER,mechanism:"cloudflare.alarm",attributes:{"faas.trigger":"timer",...S}}:St[h]?x={name:`${p} ${St[h]}`,kind:SpanKind.SERVER,mechanism:"cloudflare.websocket",attributes:{"faas.trigger":"other",...S}}:h==="scheduled"||h==="queue"?x={name:h==="scheduled"?`cron ${A[0]?.cron??""}`.trim():`${A[0]?.queue??"queue"} process`,kind:h==="queue"?SpanKind.CONSUMER:SpanKind.SERVER,mechanism:`cloudflare.${h}`,attributes:{"faas.trigger":h==="queue"?"pubsub":"timer","faas.cron":A[0]?.cron,"messaging.destination.name":A[0]?.queue}}:x={name:`${p}.${h}`,kind:SpanKind.SERVER,mechanism:"cloudflare.rpc",attributes:{"rpc.system":"cloudflare_rpc","rpc.service":p,"rpc.method":h,...S}};let kt=typeof a?.waitUntil=="function"?a:void 0;return H(c,x,kt,()=>y.apply(f,A),Ie)};return new Proxy(f,{get(h,y,A){let S=Reflect.get(h,y,A);if(typeof y!="string"||typeof S!="function"||mn.has(y)||y.startsWith("_")||S===Object.prototype[y])return S;let x=C.get(y);return x||C.set(y,x=E(y,S)),x}})}})}function bn(e){return async t=>{let n=typeof e=="function"?s=>e({...t,env:s}):e,r=Y(t.env,n,dn);if(!r)return t.next();l(()=>{for(let s of Object.keys(t.env)){let i=Ae(t.env[s],s,r);i&&(t.env[s]=i);}});let o=qe(t.request,r,"cloudflare.pages");return H(r,o,t,s=>{let i=z({waitUntil:t.waitUntil.bind(t)},s,r);return l(()=>{t.waitUntil=i.waitUntil;}),t.next()},Oe(r))}}var U=e=>(t,n)=>Z()?.emit(e,t,n),_e={traceId:"",spanId:"",setAttribute:()=>_e,setAttributes:()=>_e},Rn={captureError(e,t){Z()?.report(e,true,t);},setUser(e){l(()=>gt(e));},setTag(e,t){l(()=>pt(e,t));},log:{trace:U("trace"),debug:U("debug"),info:U("info"),warn:U("warn"),error:U("error"),fatal:U("fatal")},startSpan(e,t,n){if(!Z())return t(_e);let r=k(e,{attributes:n}),o=s=>{r.setStatus({code:SpanStatusCode.ERROR,message:W(s).message}),r.end();};try{let s=X(r,()=>t(r));return s&&typeof s.then=="function"?s.then(i=>(r.end(),i),i=>{throw o(i),i}):(r.end(),s)}catch(s){throw o(s),s}},get traceId(){return I()?.traceId},async flush(){await Z()?.flush();}},Ur=Rn;
8
+ export{N as VERSION,Rn as Zharp,Ur as default,yn as instrumentDurableObject,hn as withZharp,bn as zharpPagesPlugin};//# sourceMappingURL=index.mjs.map
9
+ //# sourceMappingURL=index.mjs.map