@lunora/observability 1.0.0-alpha.100 → 1.0.0-alpha.101
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.d.mts +12 -9
- package/dist/index.d.ts +12 -9
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{REQUEST_LOG_TABLE-D3ax4pFP.mjs → REQUEST_LOG_TABLE-COD6mJNf.mjs} +1 -1
- package/dist/packem_shared/{createDatabaseTally-BsElP16g.mjs → createDatabaseTally-j6FBQgYe.mjs} +1 -1
- package/dist/packem_shared/{createMetrics-DTJWo1fV.mjs → createMetrics-Lh0oGuDt.mjs} +1 -1
- package/dist/packem_shared/request-log-BujFR0De.mjs +24 -0
- package/package.json +2 -2
- package/dist/packem_shared/request-log-pOG0ApHK.mjs +0 -24
package/dist/index.d.mts
CHANGED
|
@@ -1724,15 +1724,18 @@ interface ReadIssuesOptions {
|
|
|
1724
1724
|
*
|
|
1725
1725
|
* On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
|
|
1726
1726
|
* fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
|
|
1727
|
-
* with a credential name are masked; `Basic
|
|
1728
|
-
*
|
|
1729
|
-
*
|
|
1730
|
-
*
|
|
1731
|
-
*
|
|
1732
|
-
*
|
|
1733
|
-
*
|
|
1734
|
-
*
|
|
1735
|
-
*
|
|
1727
|
+
* with a credential name are masked; `Basic …`, `Bearer …` and `Digest …` are
|
|
1728
|
+
* masked; and so is a bare token in prose with no name attached, when its format
|
|
1729
|
+
* has a distinctive vendor prefix (`failed with sk_live_…`, `ghp_…`, `xoxb-…`,
|
|
1730
|
+
* `AKIA…`, JWTs, … — see `SECRET_VALUE_RULES`), all by `maskCredentials`.
|
|
1731
|
+
* `standardRules`' value patterns (emails, long digit runs) then mask PII. Every
|
|
1732
|
+
* string is truncated to 4 KiB in what is stored, and once 16 KiB of one value has
|
|
1733
|
+
* been examined the remaining strings are replaced with a marker, so no arg can
|
|
1734
|
+
* hold the Durable Object in regex work.
|
|
1735
|
+
*
|
|
1736
|
+
* Still NOT caught: a bare secret with no name attached and no vendor prefix (a
|
|
1737
|
+
* random hex key, a password in a sentence). This is a credential-and-PII net,
|
|
1738
|
+
* not proof that no secret can reach the log.
|
|
1736
1739
|
*
|
|
1737
1740
|
* `captureRaw` is the development escape hatch: in a dev environment the dispatch
|
|
1738
1741
|
* site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
|
package/dist/index.d.ts
CHANGED
|
@@ -1724,15 +1724,18 @@ interface ReadIssuesOptions {
|
|
|
1724
1724
|
*
|
|
1725
1725
|
* On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
|
|
1726
1726
|
* fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
|
|
1727
|
-
* with a credential name are masked; `Basic
|
|
1728
|
-
*
|
|
1729
|
-
*
|
|
1730
|
-
*
|
|
1731
|
-
*
|
|
1732
|
-
*
|
|
1733
|
-
*
|
|
1734
|
-
*
|
|
1735
|
-
*
|
|
1727
|
+
* with a credential name are masked; `Basic …`, `Bearer …` and `Digest …` are
|
|
1728
|
+
* masked; and so is a bare token in prose with no name attached, when its format
|
|
1729
|
+
* has a distinctive vendor prefix (`failed with sk_live_…`, `ghp_…`, `xoxb-…`,
|
|
1730
|
+
* `AKIA…`, JWTs, … — see `SECRET_VALUE_RULES`), all by `maskCredentials`.
|
|
1731
|
+
* `standardRules`' value patterns (emails, long digit runs) then mask PII. Every
|
|
1732
|
+
* string is truncated to 4 KiB in what is stored, and once 16 KiB of one value has
|
|
1733
|
+
* been examined the remaining strings are replaced with a marker, so no arg can
|
|
1734
|
+
* hold the Durable Object in regex work.
|
|
1735
|
+
*
|
|
1736
|
+
* Still NOT caught: a bare secret with no name attached and no vendor prefix (a
|
|
1737
|
+
* random hex key, a password in a sentence). This is a credential-and-PII net,
|
|
1738
|
+
* not proof that no secret can reach the log.
|
|
1736
1739
|
*
|
|
1737
1740
|
* `captureRaw` is the development escape hatch: in a dev environment the dispatch
|
|
1738
1741
|
* site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as T,AUTH_METRICS_BUCKET_RETENTION as o,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-CeplWoRm.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-
|
|
1
|
+
import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as T,AUTH_METRICS_BUCKET_RETENTION as o,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-CeplWoRm.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-Lh0oGuDt.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-j6FBQgYe.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as f,FUNCTION_METRICS_BUCKET_MS as U,FUNCTION_METRICS_BUCKET_RETENTION as d,FUNCTION_METRICS_INDEX_TABLE as R,FUNCTION_METRICS_MAX_PATHS as L,FUNCTION_METRICS_READ_LIMIT as m,FUNCTION_METRICS_SCANS_TABLE as x,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as l,readFunctionMetricBuckets as g,readFunctionMetricIndexHits as O,readFunctionMetricScans as H,readFunctionMetrics as y,readFunctionMetricsTotals as b,recordFunctionMetric as D}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as K,explainIssue as q,parseExplainIssueArgs as v}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as G,ISSUE_STATE_TABLE as X,ISSUE_STATUSES as P,upsertIssueState as k}from"./packem_shared/ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{LogBuffer as j}from"./packem_shared/LogBuffer-BmD4CfV0.mjs";import{M as z}from"./packem_shared/metric-buffer-Bx0XbypU.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-TKfnwFNv.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-8nYLTftS.mjs";import{R as Te,a as oe,e as ae,b as se,c as Ee,p as _e,r as ce,d as Se,f as Ie}from"./packem_shared/request-log-BujFR0De.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as fe}from"./packem_shared/findDanglingReferences-BNgg0jD_.mjs";import{r as de}from"./packem_shared/trace-context-d_EfGPSZ.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,T as AUTH_METRICS_BUCKET_MS,o as AUTH_METRICS_BUCKET_RETENTION,a as AUTH_METRICS_TABLE,K as DEFAULT_EXPLAIN_ISSUE_MODEL,f as FUNCTION_METRICS_BUCKETS_TABLE,U as FUNCTION_METRICS_BUCKET_MS,d as FUNCTION_METRICS_BUCKET_RETENTION,R as FUNCTION_METRICS_INDEX_TABLE,L as FUNCTION_METRICS_MAX_PATHS,m as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,G as ISSUE_SEVERITIES,X as ISSUE_STATE_TABLE,P as ISSUE_STATUSES,j as LogBuffer,ne as MIN_ADMIN_TOKEN_LENGTH,Me as MIN_AUTH_SECRET_LENGTH,z as MetricBuffer,Te as REQUEST_LOG_TABLE,Ce as SpanBuffer,oe as appendRequestLogEntry,ue as buildSecurityAudit,A as createDatabaseTally,S as createMetrics,I as createSpanCollector,i as createTracedFetch,n as createTracer,M as dispatchRootSpan,ae as emitLogEvent,se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Ee as ensureRequestLogTable,q as explainIssue,fe as findDanglingReferences,Ne as foldTraces,C as formatTally,N as instrumentDatabase,l as mergeScanAttribution,v as parseExplainIssueArgs,_e as parseLogArgs,E as readAuthMetrics,ce as readErrorIssues,g as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,H as readFunctionMetricScans,y as readFunctionMetrics,b as readFunctionMetricsTotals,W as readMetricHistory,$ as readQueryInsights,ee as readQueryMetrics,Se as readRequestLog,_ as recordAuthEvent,D as recordFunctionMetric,Y as recordMetricHistory,re as recordQueryMetric,Ie as redactArgs,de as resolveTraceAnchor,k as upsertIssueState};
|
package/dist/packem_shared/{REQUEST_LOG_TABLE-D3ax4pFP.mjs → REQUEST_LOG_TABLE-COD6mJNf.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as t,R as o,a as g,e as E,b as L,c as R,p as d,r as p,d as n,f as u,g as T,i}from"./request-log-
|
|
1
|
+
import{h as t,R as o,a as g,e as E,b as L,c as R,p as d,r as p,d as n,f as u,g as T,i}from"./request-log-BujFR0De.mjs";import"./ISSUE_SEVERITIES-gLC4VEPQ.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as appendRequestLogEntry,E as emitLogEvent,L as emitRequestLogEvent,R as ensureRequestLogTable,d as parseLogArgs,p as readErrorIssues,n as readRequestLog,u as redactArgs,T as redactSecrets,i as renderLogMessage};
|
package/dist/packem_shared/{createDatabaseTally-BsElP16g.mjs → createDatabaseTally-j6FBQgYe.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as m,t as b}from"./trace-context-d_EfGPSZ.mjs";import{f as M}from"./request-log-
|
|
1
|
+
import{o as m,t as b}from"./trace-context-d_EfGPSZ.mjs";import{f as M}from"./request-log-BujFR0De.mjs";const y=100,T=new Set(["aggregate","count","delete","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","related","replace","restore"]),w=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),S=(e,t)=>{if(!w.has(e))return;const n=t[0];return typeof n=="string"&&n.length>0?n:void 0},k=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),E=e=>{const{deps:t,durationMs:n,failure:a,operation:s,startTs:r,table:o}=e;return{attributes:{"db.operation.name":s,...o===void 0?{}:{"db.collection.name":o},"db.system.name":"sqlite"},durationMs:n,...a===void 0?{}:{error:{message:M(k(a),t.captureRaw),type:b(a)}},functionPath:t.functionPath,kind:"client",name:o===void 0?`db.${s}`:`db.${s} ${o}`,ok:a===void 0,parentSpanId:t.anchor.rootSpanId,shardKey:t.shardKey,spanId:m(8),startTs:r,traceId:t.anchor.traceId,userId:t.userId()}},v=(e,t)=>{if(t.mode==="off")return e;const{tally:n}=t,a=new Map;return new Proxy(e,{get(s,r,o){const c=Reflect.get(s,r,o);if(typeof r!="string"||typeof c!="function"||!T.has(r))return c;const f=a.get(r);if(f!==void 0)return f;const g=c,u=async(...p)=>{const l=Date.now(),h=S(r,p);let d;try{return await g.apply(s,p)}catch(i){throw d=i,i}finally{const i=Date.now()-l;n.calls+=1,n.durationMs+=i,n.perOperation[r]=(n.perOperation[r]??0)+1,d!==void 0&&(n.errors+=1);try{t.mode==="spans"&&(n.spansEmitted>=y?n.spansTruncated=!0:(n.spansEmitted+=1,t.record(E({deps:t,durationMs:i,failure:d,operation:r,startTs:l,table:h}))))}catch{}}};return a.set(r,u),u}})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),P=e=>{const t={"db.calls":e.calls,"db.duration_ms":e.durationMs};e.errors>0&&(t["db.errors"]=e.errors),e.spansTruncated&&(t["db.spans_truncated"]=!0);for(const[n,a]of Object.entries(e.perOperation))t[`db.op.${n}`]=a;return t};export{D as createDatabaseTally,P as formatTally,v as instrumentDatabase};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as O,g as A,n as I}from"./request-log-
|
|
1
|
+
import{f as O,g as A,n as I}from"./request-log-BujFR0De.mjs";import{L as g,o as K,b as D,t as P,O as U}from"./trace-context-d_EfGPSZ.mjs";const F=/[\w.-]/u,q=t=>{let e="";for(const r of t)e+=F.test(r)?r:"_";return e},C=t=>{if(typeof t.name!="string"||t.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new TypeError("recordEvaluation `score` must be a finite number");const e=q(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},X=t=>{const e=Object.keys(t);if(e.length===0||!e.every(o=>o==="attributes"||o==="kind"||o==="links"))return!1;const{kind:r}=t;return r===void 0||Object.hasOwn(U,r)},B=128,V=128,L=128,m=(t,e)=>{if(e===void 0)return;let r=Object.keys(t).length;for(const[o,s]of Object.entries(e)){const n=!Object.hasOwn(t,o);n&&r>=L||(n&&(r+=1),t[o]=s)}},H=t=>{const e=I(t);if(e===void 0||Object.keys(e).length<=L)return e;const r={};return m(r,e),r},G=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},J=t=>{try{return new URL(t).host}catch{return t}},Q=(t,e)=>{try{return t(new URL(e))}catch{return!1}},W=t=>t===void 0?{}:X(t)?t:{attributes:t},Y=(t,e)=>{if(t.isTraced){t.setAttribute(g.functionPath,e.functionPath),t.setAttribute(g.ok,e.ok),t.setAttribute(g.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(g.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(g.userId,e.userId),e.error!==void 0&&(t.setAttribute(g.errorType,e.error.type),t.setAttribute(g.errorMessage,e.error.message));for(const[r,o]of Object.entries(e.attributes))(typeof o=="boolean"||typeof o=="number"||typeof o=="string")&&t.setAttribute(`lunora.attr.${r}`,o)}},Z=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},o={spanContext:()=>t,addEvent:(s,n)=>{if(r.events.length>=B)return;const a=A(H(n),e);r.events.push({...a===void 0?{}:{attributes:a},name:s,ts:Date.now()})},addLink:s=>{if(r.links.length>=V)return;const n=A(H(s.attributes),e);r.links.push({...n===void 0?{}:{attributes:n},spanId:s.spanId,traceId:s.traceId})},recordEvaluation:s=>{m(r.attributes,I(C(s)))},recordException:s=>{const n=s instanceof Error?s.message:String(s);o.addEvent("exception",{"exception.message":O(n,e),...e&&s instanceof Error&&typeof s.stack=="string"?{"exception.stacktrace":s.stack}:{},"exception.type":P(s)})},setAttribute:(s,n)=>{m(r.attributes,I({[s]:n}))},setAttributes:s=>{m(r.attributes,I(s))}};return{collected:r,handle:o}},rt=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:o,functionPath:s,record:n,resolveHostTracing:a,shardKey:c,userId:p}=t,d=y=>async(k,T,u,M)=>{const l=M?.spanId??K(8),w=M?.parentSpanId??y,i=Date.now(),b=W(u),x=I(b.attributes),{collected:E,handle:z}=Z({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:l,traceId:e.traceId},r),$=async S=>{let f=!0,v;try{return await T(d(l),z)}catch(h){f=!1;const _=h instanceof Error?h.message:String(h);throw v={message:O(_,r),type:P(h)},h}finally{const h=Date.now()-i,_=p(),N={};m(N,x),m(N,E.attributes);const R=A(N,r),j=[...b.links??[],...E.links];try{n({...Object.keys(R).length===0?{}:{attributes:R},durationMs:h,...E.events.length===0?{}:{events:E.events},...v===void 0?{}:{error:v},functionPath:s,...b.kind===void 0||b.kind==="internal"?{}:{kind:b.kind},...j.length===0?{}:{links:j},name:k,ok:f,parentSpanId:w,shardKey:c,spanId:l,startTs:i,traceId:e.traceId,userId:_})}catch{}if(S!==void 0)try{Y(S,{attributes:R,durationMs:h,error:v,functionPath:s,ok:f,shardKey:c,userId:_})}catch{}}};if(o===!0&&a!==void 0){let S=!1;try{const f=await a();if(f!==void 0&&typeof f.enterSpan=="function")return await f.enterSpan(k,v=>(S=!0,$(v)))}catch(f){if(S)throw f}}return await $()};return d(e.rootSpanId)},st=(t,e)=>{const{anchor:r,captureRaw:o=!1,functionPath:s,propagate:n=!0,record:a,shardKey:c,userId:p}=t;return async(d,y)=>{const k=K(8),T=Date.now(),u=new Request(d,y);(typeof n=="function"?Q(n,u.url):n)&&u.headers.set("traceparent",D(r.traceId,k,r.sampled??!0));let l,w;try{const i=await e(u);return w=i.status,i.ok||(l={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const b=i instanceof Error?i.message:String(i);throw l={message:O(b,o),type:P(i)},i}finally{try{a({attributes:{"http.request.method":u.method,...w===void 0?{}:{"http.response.status_code":w},"url.full":G(u.url)},durationMs:Date.now()-T,...l===void 0?{}:{error:l},functionPath:s,kind:"client",name:`${u.method} ${J(u.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,shardKey:c,spanId:k,startTs:T,traceId:r.traceId,userId:p()})}catch{}}}},nt=t=>{const{functionPath:e,record:r,shardKey:o}=t,s=(n,a,c,p)=>{if(!Number.isFinite(c))return;const d=A(I(p));try{r({...d===void 0?{}:{attributes:d},functionPath:e,kind:n,name:a,shardKey:o,ts:Date.now(),value:c})}catch{}};return{count:(n,a=1,c)=>{s("counter",n,a,c)},gauge:(n,a,c)=>{s("gauge",n,a,c)},record:(n,a,c)=>{s("histogram",n,a,c)}}},ot=t=>{const{anchor:e,captureRaw:r=!1,collected:o,durationMs:s,failure:n,functionPath:a,shardKey:c,startTs:p,userId:d}=t,y=A(o?.attributes??{},r);return{...Object.keys(y).length===0?{}:{attributes:y},dispatch:!0,durationMs:s,...o===void 0||o.events.length===0?{}:{events:o.events},...n===void 0?{}:{error:{message:O(n.thrown instanceof Error?n.thrown.message:String(n.thrown),r),type:P(n.thrown)}},functionPath:a,...o===void 0||o.links.length===0?{}:{links:o.links},name:a,ok:n===void 0,parentSpanId:"",shardKey:c,spanId:e.rootSpanId,startTs:p,traceId:e.traceId,userId:d}};export{Y as applyHostSpanAttributes,nt as createMetrics,Z as createSpanCollector,st as createTracedFetch,rt as createTracer,ot as dispatchRootSpan};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{fingerprintError as M}from"@lunora/fingerprint";import{createRedactor as G,standardRules as X}from"@visulima/redact";import{readIssueStates as z}from"./ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const H=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},O=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:H(e),I=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[r,n]of Object.entries(t))s[r]=O(n);if(e!==void 0)for(const[r,n]of Object.entries(e))s[r]=O(n);return Object.keys(s).length===0?void 0:s},V=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),J=new Set(["card","pass","pin","session"]),Z=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),K=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),B=new Set(["card no","connection string","database url","one time"]),Y=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],q=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Q=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),ee=new Set(["max","min","num","total"]),T=4096,te=128,se=16384,u="<REDACTED>",re="[redaction budget exceeded]",ne=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),N=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,oe=(e,t)=>{const s=N(e[t]),r=t>0?N(e[t-1]):void 0;if(V.has(s))return s;if(r!==void 0){if(s==="key"&&Z.has(r))return"key";if(s==="code"&&K.has(r))return"code";if(B.has(`${r} ${s}`))return`${r} ${s}`}return Y.some(n=>s.endsWith(n))?s:void 0},D=e=>{const t=ne(e);if(t.length===0)return"none";const s=Q.has(t.at(-1))||ee.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=oe(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(a=>q.has(a))?J.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},ie=e=>typeof e=="boolean"||e===null||e===void 0?e:u,ae=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),a=r.indexOf(":"),c=r.indexOf("/"),o=a!==-1&&/^\d+$/.test(r.slice(a+1,c===-1?void 0:c)),i=a!==-1&&!o&&(c===-1||a<c);if(n===-1&&i&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(c===-1||n<c||a!==-1&&a<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},ce=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,de=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,le=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,$=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,C=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],fe=String.raw`(?<=^|[^\w-]|${$})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ue=new RegExp([...C.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${$})${t}${e}`),fe].join("|"),"g"),ge=new RegExp([...C.map(({prefix:e})=>e),"eyJ"].join("|")),pe=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,S=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,L=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,k=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,he=e=>{let t="",s=0;S.lastIndex=0;for(let r=S.exec(e);r!==null;r=S.exec(e)){const n=D(r[2]),a=r.index+r[0].length;L.lastIndex=a;const c=n==="none"?null:L.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){S.lastIndex=Math.max(a,r.index+1);continue}const o=c[0],i=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=a+o.length;i===""&&r[3]===":"&&(k.lastIndex=d,d+=k.exec(e)?.[0].length??0),t+=`${e.slice(s,a)}${i}${u}${o.length>i.length&&o.endsWith(i)?i:""}`,s=d,S.lastIndex=s}return t+e.slice(s)},Ee=/[:=@]|basic|bearer|digest|-u\b|--/i,_e=e=>{const t=ge.test(e);if(!t&&!Ee.test(e))return e;const s=e.replaceAll(de,`-----BEGIN $1-----${u}`).replaceAll(ce,ae).replaceAll(le,`$1 ${u}`);return he((t?s.replaceAll(ue,u):s).replaceAll(pe,`$1$2$3${u}`))},Se=(e,t)=>{if(t.remaining<=0)return re;const s=e.slice(0,T+te);t.remaining-=s.length;const r=_e(s);return r.length>T||e.length>s.length?`${r.slice(0,T)}…[truncated]`:r},me=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),m=Symbol("no-json"),Ae=e=>{const{toJSON:t}=e;if(typeof t!="function")return m;try{const s=t.call(e);return s===e?m:s}catch{return m}},Te=32,A=(e,t,s,r,n)=>{if(typeof e=="string")return r?u:Se(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&me(e))return e;if(t.has(e)||s>=Te)return u;const a=Array.isArray(e)?m:Ae(e);if(a!==m){t.add(e);const o=A(a,t,s+1,r,n);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>A(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,i])=>{const d=D(o);return d==="secret"||d==="scalar-secret"&&(typeof i!="object"||i===null)?[o,ie(i)]:[o,A(i,t,s+1,d==="count-secret"&&(typeof i=="string"||Array.isArray(i)),n)]}));return t.delete(e),c},U=e=>A(e,new WeakSet,0,!1,{remaining:se}),p="__lunora_reqlog__",y=1e3,P="lunora",ye=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],be=G(X,{exclude:["pass"]}),Ce=(e,t=!1)=>t||e===null||e===void 0?e:U(e),g=(e,t=!1)=>t||e===null||e===void 0?e:be(U(e)),w=new WeakSet,b=e=>{if(!w.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${p}" (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
function_path TEXT NOT NULL,
|
|
5
|
+
shard_key TEXT,
|
|
6
|
+
user_id TEXT,
|
|
7
|
+
identity TEXT,
|
|
8
|
+
args TEXT,
|
|
9
|
+
outcome TEXT NOT NULL,
|
|
10
|
+
error_message TEXT,
|
|
11
|
+
error_fingerprint TEXT,
|
|
12
|
+
trace_id TEXT,
|
|
13
|
+
deployment_id TEXT,
|
|
14
|
+
version_tag TEXT,
|
|
15
|
+
duration_ms REAL NOT NULL,
|
|
16
|
+
tables_read TEXT NOT NULL DEFAULT '[]',
|
|
17
|
+
tables_written TEXT NOT NULL DEFAULT '[]',
|
|
18
|
+
cache_hit INTEGER,
|
|
19
|
+
subscriptions_rerun INTEGER NOT NULL DEFAULT 0
|
|
20
|
+
)`);for(const t of ye)try{E(e,`ALTER TABLE "${p}" ADD COLUMN ${t}`)}catch{}w.add(e)}},v=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Re=e=>e===void 0?null:e?1:0,Ue=(e,t,s={})=>{b(e);const r=s.captureRaw??!1,n=s.retention??y,a=t.outcome==="error"&&t.errorMessage!==void 0?M({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${p}"
|
|
21
|
+
(ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
|
|
22
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(g(t.identity,r)),t.redactedArgs===void 0?null:JSON.stringify(g(t.redactedArgs,r)),t.outcome,t.errorMessage===void 0?null:g(t.errorMessage,r),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,v(t.tablesRead),v(t.tablesWritten),Re(t.cacheHit),t.subscriptionsReRun??0),E(e,`DELETE FROM "${p}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${p}")`,n)},Pe=(e,t={})=>{const s=t.captureRaw??!1,r={args:e.redactedArgs===void 0?void 0:g(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:g(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:g(e.identity,s),outcome:e.outcome,shard:e.shardKey,source:P,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},n=JSON.stringify(r);e.outcome==="error"?console.error(n):console.log(n)},Oe="log",Ie=e=>e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}).join(" "),Ne=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},We=(e,t)=>e.length===2&&typeof e[0]=="string"&&Ne(e[1])?{fields:I(e[1],t),message:e[0]}:{fields:I(void 0,t),message:Ie(e)},je=(e,t={})=>{const s=t.captureRaw??!1,r={fields:e.fields===void 0?void 0:g(e.fields,s),function:e.functionPath,level:e.level,message:g(e.message,s),shard:e.shardKey,source:P,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Oe,userId:e.userId};let n;try{n=JSON.stringify(r)}catch{n=JSON.stringify({...r,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(n):e.level==="warn"?console.warn(n):console.log(n)},Le=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,W=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(Le("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},x=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},ke=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},we=e=>{try{return JSON.parse(e)}catch{return}},Fe=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(W(r,n,t),t.outcome!==void 0&&(r.push("outcome = ?"),n.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);r.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),n.push(o,o)}n.push(s);const a=t.sinceSeq===void 0?"DESC":"ASC";return E(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
|
|
23
|
+
FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,...n).toArray().map(o=>{const i={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:x(o.tables_read),tablesWritten:x(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(i.shardKey=o.shard_key),o.user_id!==null&&(i.userId=o.user_id),o.identity!==null){const d=ke(o.identity);d!==void 0&&(i.identity=d)}if(o.args!==null){const d=we(o.args);d!==void 0&&(i.redactedArgs=d)}return o.error_message!==null&&(i.errorMessage=o.error_message),o.cache_hit!==null&&(i.cacheHit=o.cache_hit===1),o.trace_id!==null&&(i.traceId=o.trace_id),o.deployment_id!==null&&(i.deploymentId=o.deployment_id),o.version_tag!==null&&(i.versionTag=o.version_tag),i})},ve=(e,t)=>{const s=z(e,[...t.keys()]);for(const r of t.values()){const n=s.get(r.hash);n!==void 0&&(r.stateUpdatedAt=n.updatedAt,n.assignee!==void 0&&(r.assignee=n.assignee),n.severity!==void 0&&(r.severity=n.severity),r.status=n.status==="resolved"&&r.lastSeen>n.updatedAt?"open":n.status)}},Ge=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["outcome = 'error'"],n=[];W(r,n,t),n.push(s);const a=E(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
24
|
+
FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of a){const _=l.error_message??"",{culprit:j,hash:F,title:R}=M({functionPath:l.function_path,message:_}),h=l.error_fingerprint??F,f=c.get(h);if(f===void 0){c.set(h,{count:1,culprit:j,firstSeen:l.ts,hash:h,lastSeen:l.ts,sampleMessage:_,status:"open",title:R}),o.set(h,l.ts);continue}f.count+=1,f.firstSeen=Math.min(f.firstSeen,l.ts),f.lastSeen=Math.max(f.lastSeen,l.ts),l.ts>(o.get(h)??Number.NEGATIVE_INFINITY)&&(o.set(h,l.ts),f.sampleMessage=_,f.title=R)}ve(e,c);const i=[...c.values()];return(t.status===void 0?i:i.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{p as R,Ue as a,Pe as b,b as c,Fe as d,je as e,g as f,Ce as g,y as h,Ie as i,I as n,We as p,Ge as r};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/observability",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.101",
|
|
4
4
|
"description": "Host-neutral telemetry storage and read models for Lunora, backing the Studio's Logs, Traces, Metrics and Issues views",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"lunora",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@lunora/errors": "1.0.0-alpha.44",
|
|
47
47
|
"@lunora/fingerprint": "1.0.0-alpha.9",
|
|
48
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
48
|
+
"@lunora/shard-engine": "1.0.0-alpha.92",
|
|
49
49
|
"@visulima/redact": "5.0.0"
|
|
50
50
|
},
|
|
51
51
|
"engines": {
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import{fingerprintError as $}from"@lunora/fingerprint";import{createRedactor as X,standardRules as j}from"@visulima/redact";import{readIssueStates as F}from"./ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{r as p}from"./run-sql-0aPgJkIw.mjs";const K=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},I=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:K(e),N=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[r,n]of Object.entries(t))s[r]=I(n);if(e!==void 0)for(const[r,n]of Object.entries(e))s[r]=I(n);return Object.keys(s).length===0?void 0:s},G=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),J=new Set(["card","pass","pin","session"]),V=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),H=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),q=new Set(["card no","connection string","database url","one time"]),z=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],B=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Y=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),Z=new Set(["max","min","num","total"]),O=4096,Q=16384,f="<REDACTED>",ee="[redaction budget exceeded]",te=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),L=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,se=(e,t)=>{const s=L(e[t]),r=t>0?L(e[t-1]):void 0;if(G.has(s))return s;if(r!==void 0){if(s==="key"&&V.has(r))return"key";if(s==="code"&&H.has(r))return"code";if(q.has(`${r} ${s}`))return`${r} ${s}`}return z.some(n=>s.endsWith(n))?s:void 0},U=e=>{const t=te(e);if(t.length===0)return"none";const s=Y.has(t.at(-1))||Z.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=se(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(a=>B.has(a))?J.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},re=e=>typeof e=="boolean"||e===null||e===void 0?e:f,ne=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),a=r.indexOf(":"),c=r.indexOf("/"),o=a!==-1&&/^\d+$/.test(r.slice(a+1,c===-1?void 0:c)),i=a!==-1&&!o&&(c===-1||a<c);if(n===-1&&i&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(c===-1||n<c||a!==-1&&a<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},oe=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,ie=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,ae=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}|\beyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*|\bAKIA[\dA-Z]{16}\b/g,ce=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,T=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,b=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,M=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,de=e=>{let t="",s=0;T.lastIndex=0;for(let r=T.exec(e);r!==null;r=T.exec(e)){const n=U(r[2]),a=r.index+r[0].length;b.lastIndex=a;const c=n==="none"?null:b.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){T.lastIndex=Math.max(a,r.index+1);continue}const o=c[0],i=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=a+o.length;i===""&&r[3]===":"&&(M.lastIndex=d,d+=M.exec(e)?.[0].length??0),t+=`${e.slice(s,a)}${i}${f}${o.length>i.length&&o.endsWith(i)?i:""}`,s=d,T.lastIndex=s}return t+e.slice(s)},le=/[:=@]|basic|bearer|digest|eyJ|AKIA|-u\b|--/i,ue=(e,t)=>{if(t.remaining<=0)return ee;const s=e.length>O?`${e.slice(0,O)}…[truncated]`:e;return t.remaining-=s.length,le.test(s)?de(s.replaceAll(ie,`-----BEGIN $1-----${f}`).replaceAll(oe,ne).replaceAll(ae,(r,n)=>n===void 0?f:`${n} ${f}`).replaceAll(ce,`$1$2$3${f}`)):s},fe=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),m=Symbol("no-json"),he=e=>{const{toJSON:t}=e;if(typeof t!="function")return m;try{const s=t.call(e);return s===e?m:s}catch{return m}},ge=32,A=(e,t,s,r,n)=>{if(typeof e=="string")return r?f:ue(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&fe(e))return e;if(t.has(e)||s>=ge)return f;const a=Array.isArray(e)?m:he(e);if(a!==m){t.add(e);const o=A(a,t,s+1,r,n);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>A(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,i])=>{const d=U(o);return d==="secret"||d==="scalar-secret"&&(typeof i!="object"||i===null)?[o,re(i)]:[o,A(i,t,s+1,d==="count-secret"&&(typeof i=="string"||Array.isArray(i)),n)]}));return t.delete(e),c},C=e=>A(e,new WeakSet,0,!1,{remaining:Q}),g="__lunora_reqlog__",S=1e3,w="lunora",Ee=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],pe=X(j,{exclude:["pass"]}),Me=(e,t=!1)=>t||e===null||e===void 0?e:C(e),h=(e,t=!1)=>t||e===null||e===void 0?e:pe(C(e)),v=new WeakSet,y=e=>{if(!v.has(e)){p(e,`CREATE TABLE IF NOT EXISTS "${g}" (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
function_path TEXT NOT NULL,
|
|
5
|
-
shard_key TEXT,
|
|
6
|
-
user_id TEXT,
|
|
7
|
-
identity TEXT,
|
|
8
|
-
args TEXT,
|
|
9
|
-
outcome TEXT NOT NULL,
|
|
10
|
-
error_message TEXT,
|
|
11
|
-
error_fingerprint TEXT,
|
|
12
|
-
trace_id TEXT,
|
|
13
|
-
deployment_id TEXT,
|
|
14
|
-
version_tag TEXT,
|
|
15
|
-
duration_ms REAL NOT NULL,
|
|
16
|
-
tables_read TEXT NOT NULL DEFAULT '[]',
|
|
17
|
-
tables_written TEXT NOT NULL DEFAULT '[]',
|
|
18
|
-
cache_hit INTEGER,
|
|
19
|
-
subscriptions_rerun INTEGER NOT NULL DEFAULT 0
|
|
20
|
-
)`);for(const t of Ee)try{p(e,`ALTER TABLE "${g}" ADD COLUMN ${t}`)}catch{}v.add(e)}},k=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),_e=e=>e===void 0?null:e?1:0,ve=(e,t,s={})=>{y(e);const r=s.captureRaw??!1,n=s.retention??S,a=t.outcome==="error"&&t.errorMessage!==void 0?$({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;p(e,`INSERT INTO "${g}"
|
|
21
|
-
(ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
|
|
22
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(h(t.identity,r)),t.redactedArgs===void 0?null:JSON.stringify(h(t.redactedArgs,r)),t.outcome,t.errorMessage===void 0?null:h(t.errorMessage,r),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,k(t.tablesRead),k(t.tablesWritten),_e(t.cacheHit),t.subscriptionsReRun??0),p(e,`DELETE FROM "${g}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${g}")`,n)},ke=(e,t={})=>{const s=t.captureRaw??!1,r={args:e.redactedArgs===void 0?void 0:h(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:h(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:h(e.identity,s),outcome:e.outcome,shard:e.shardKey,source:w,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},n=JSON.stringify(r);e.outcome==="error"?console.error(n):console.log(n)},Te="log",me=e=>e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}).join(" "),Ae=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},De=(e,t)=>e.length===2&&typeof e[0]=="string"&&Ae(e[1])?{fields:N(e[1],t),message:e[0]}:{fields:N(void 0,t),message:me(e)},$e=(e,t={})=>{const s=t.captureRaw??!1,r={fields:e.fields===void 0?void 0:h(e.fields,s),function:e.functionPath,level:e.level,message:h(e.message,s),shard:e.shardKey,source:w,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Te,userId:e.userId};let n;try{n=JSON.stringify(r)}catch{n=JSON.stringify({...r,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(n):e.level==="warn"?console.warn(n):console.log(n)},Se=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,x=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(Se("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},D=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},ye=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Re=e=>{try{return JSON.parse(e)}catch{return}},Ue=(e,t={})=>{y(e);const s=Math.max(1,Math.min(t.limit??S,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(x(r,n,t),t.outcome!==void 0&&(r.push("outcome = ?"),n.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);r.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),n.push(o,o)}n.push(s);const a=t.sinceSeq===void 0?"DESC":"ASC";return p(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
|
|
23
|
-
FROM "${g}" WHERE ${r.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,...n).toArray().map(o=>{const i={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:D(o.tables_read),tablesWritten:D(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(i.shardKey=o.shard_key),o.user_id!==null&&(i.userId=o.user_id),o.identity!==null){const d=ye(o.identity);d!==void 0&&(i.identity=d)}if(o.args!==null){const d=Re(o.args);d!==void 0&&(i.redactedArgs=d)}return o.error_message!==null&&(i.errorMessage=o.error_message),o.cache_hit!==null&&(i.cacheHit=o.cache_hit===1),o.trace_id!==null&&(i.traceId=o.trace_id),o.deployment_id!==null&&(i.deploymentId=o.deployment_id),o.version_tag!==null&&(i.versionTag=o.version_tag),i})},Ie=(e,t)=>{const s=F(e,[...t.keys()]);for(const r of t.values()){const n=s.get(r.hash);n!==void 0&&(r.stateUpdatedAt=n.updatedAt,n.assignee!==void 0&&(r.assignee=n.assignee),n.severity!==void 0&&(r.severity=n.severity),r.status=n.status==="resolved"&&r.lastSeen>n.updatedAt?"open":n.status)}},Ce=(e,t={})=>{y(e);const s=Math.max(1,Math.min(t.limit??S,1e4)),r=["outcome = 'error'"],n=[];x(r,n,t),n.push(s);const a=p(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
24
|
-
FROM "${g}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of a){const _=l.error_message??"",{culprit:P,hash:W,title:R}=$({functionPath:l.function_path,message:_}),E=l.error_fingerprint??W,u=c.get(E);if(u===void 0){c.set(E,{count:1,culprit:P,firstSeen:l.ts,hash:E,lastSeen:l.ts,sampleMessage:_,status:"open",title:R}),o.set(E,l.ts);continue}u.count+=1,u.firstSeen=Math.min(u.firstSeen,l.ts),u.lastSeen=Math.max(u.lastSeen,l.ts),l.ts>(o.get(E)??Number.NEGATIVE_INFINITY)&&(o.set(E,l.ts),u.sampleMessage=_,u.title=R)}Ie(e,c);const i=[...c.values()];return(t.status===void 0?i:i.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{g as R,ve as a,ke as b,y as c,Ue as d,$e as e,h as f,Me as g,S as h,me as i,N as n,De as p,Ce as r};
|