@prisma/extension-optimize 0.0.0-dev.202412312046 → 0.0.0-dev.202501011234

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var yt=Object.create;var _=Object.defineProperty;var ht=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var Rt=(e,t)=>{for(var n in t)_(e,n,{get:t[n],enumerable:!0})},xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of St(t))!bt.call(e,s)&&s!==n&&_(e,s,{get:()=>t[s],enumerable:!(r=ht(t,s))||r.enumerable});return e};var It=(e,t,n)=>(n=e!=null?yt(xt(e)):{},xe(t||!e||!e.__esModule?_(n,"default",{value:e,enumerable:!0}):n,e)),wt=e=>xe(_({},"__esModule",{value:!0}),e);var pn={};Rt(pn,{PROD_DASHBOARD_URL:()=>dt,PROD_INGESTION_URL:()=>mt,withOptimize:()=>cn});module.exports=wt(pn);var lt=require("@opentelemetry/api"),ft=require("@prisma/client/extension");var M=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(t,n){this.keyToValue.set(t,n),this.valueToKey.set(n,t)}getByKey(t){return this.keyToValue.get(t)}getByValue(t){return this.valueToKey.get(t)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}};var O=class{constructor(t){this.generateIdentifier=t,this.kv=new M}register(t,n){this.kv.getByValue(t)||(n||(n=this.generateIdentifier(t)),this.kv.set(n,t))}clear(){this.kv.clear()}getIdentifier(t){return this.kv.getByValue(t)}getValue(t){return this.kv.getByKey(t)}};var L=class extends O{constructor(){super(t=>t.name),this.classToAllowedProps=new Map}register(t,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(t,n.allowProps),super.register(t,n.identifier)):super.register(t,n)}getAllowedProps(t){return this.classToAllowedProps.get(t)}};function Tt(e){if("values"in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function be(e,t){let n=Tt(e);if("find"in n)return n.find(t);let r=n;for(let s=0;s<r.length;s++){let o=r[s];if(t(o))return o}}function v(e,t){Object.entries(e).forEach(([n,r])=>t(r,n))}function A(e,t){return e.indexOf(t)!==-1}function ee(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var U=class{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return be(this.transfomers,n=>n.isApplicable(t))}findByName(t){return this.transfomers[t]}};var vt=e=>Object.prototype.toString.call(e).slice(8,-1),te=e=>typeof e>"u",Et=e=>e===null,E=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,V=e=>E(e)&&Object.keys(e).length===0,g=e=>Array.isArray(e),qt=e=>typeof e=="string",Ot=e=>typeof e=="number"&&!isNaN(e),At=e=>typeof e=="boolean",Re=e=>e instanceof RegExp,x=e=>e instanceof Map,b=e=>e instanceof Set,ne=e=>vt(e)==="Symbol",Ie=e=>e instanceof Date&&!isNaN(e.valueOf()),we=e=>e instanceof Error,re=e=>typeof e=="number"&&isNaN(e),Te=e=>At(e)||Et(e)||te(e)||Ot(e)||qt(e)||ne(e),ve=e=>typeof e=="bigint",Ee=e=>e===1/0||e===-1/0,qe=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Oe=e=>e instanceof URL;var se=e=>e.replace(/\./g,"\\."),B=e=>e.map(String).map(se).join("."),P=e=>{let t=[],n="";for(let s=0;s<e.length;s++){let o=e.charAt(s);if(o==="\\"&&e.charAt(s+1)==="."){n+=".",s++;continue}if(o==="."){t.push(n),n="";continue}n+=o}let r=n;return t.push(r),t};function h(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Ae=[h(te,"undefined",()=>null,()=>{}),h(ve,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),h(Ie,"Date",e=>e.toISOString(),e=>new Date(e)),h(we,"Error",(e,t)=>{let n={name:e.name,message:e.message};return t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n},(e,t)=>{let n=new Error(e.message);return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n}),h(Re,"regexp",e=>""+e,e=>{let t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),h(b,"set",e=>[...e.values()],e=>new Set(e)),h(x,"map",e=>[...e.entries()],e=>new Map(e)),h(e=>re(e)||Ee(e),"number",e=>re(e)?"NaN":e>0?"Infinity":"-Infinity",Number),h(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),h(Oe,"URL",e=>e.toString(),e=>new URL(e))];function D(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Pe=D((e,t)=>ne(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown symbol");return r}),Pt=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),Ce=D(qe,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{let n=Pt[t[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function ie(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var ke=D(ie,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(s=>{r[s]=e[s]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),ze=D((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw new Error("Trying to deserialize unknown custom value");return r.deserialize(e)}),Ct=[ke,Pe,ze,Ce],oe=(e,t)=>{let n=ee(Ct,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=ee(Ae,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},je={};Ae.forEach(e=>{je[e.annotation]=e});var Ne=(e,t,n)=>{if(g(t))switch(t[0]){case"symbol":return Pe.untransform(e,t,n);case"class":return ke.untransform(e,t,n);case"custom":return ze.untransform(e,t,n);case"typed-array":return Ce.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{let r=je[t];if(!r)throw new Error("Unknown transformation: "+t);return r.untransform(e,n)}};var C=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function _e(e){if(A(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(A(e,"prototype"))throw new Error("prototype is not allowed as a property");if(A(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Me=(e,t)=>{_e(t);for(let n=0;n<t.length;n++){let r=t[n];if(b(e))e=C(e,+r);else if(x(e)){let s=+r,o=+t[++n]==0?"key":"value",c=C(e,s);switch(o){case"key":e=c;break;case"value":e=e.get(c);break}}else e=e[r]}return e},Q=(e,t,n)=>{if(_e(t),t.length===0)return n(e);let r=e;for(let o=0;o<t.length-1;o++){let c=t[o];if(g(r)){let u=+c;r=r[u]}else if(E(r))r=r[c];else if(b(r)){let u=+c;r=C(r,u)}else if(x(r)){if(o===t.length-2)break;let l=+c,S=+t[++o]==0?"key":"value",d=C(r,l);switch(S){case"key":r=d;break;case"value":r=r.get(d);break}}}let s=t[t.length-1];if(g(r)?r[+s]=n(r[+s]):E(r)&&(r[s]=n(r[s])),b(r)){let o=C(r,+s),c=n(o);o!==c&&(r.delete(o),r.add(c))}if(x(r)){let o=+t[t.length-2],c=C(r,o);switch(+s==0?"key":"value"){case"key":{let l=n(c);r.set(l,r.get(c)),l!==c&&r.delete(c);break}case"value":{r.set(c,n(r.get(c)));break}}}return e};function ae(e,t,n=[]){if(!e)return;if(!g(e)){v(e,(o,c)=>ae(o,t,[...n,...P(c)]));return}let[r,s]=e;s&&v(s,(o,c)=>{ae(o,t,[...n,...P(c)])}),t(r,n)}function Le(e,t,n){return ae(t,(r,s)=>{e=Q(e,s,o=>Ne(o,r,n))}),e}function Ue(e,t){function n(r,s){let o=Me(e,P(s));r.map(P).forEach(c=>{e=Q(e,c,()=>o)})}if(g(t)){let[r,s]=t;r.forEach(o=>{e=Q(e,P(o),()=>e)}),s&&v(s,n)}else v(t,n);return e}var kt=(e,t)=>E(e)||g(e)||x(e)||b(e)||ie(e,t);function zt(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function Ve(e,t){let n={},r;return e.forEach(s=>{if(s.length<=1)return;t||(s=s.map(u=>u.map(String)).sort((u,l)=>u.length-l.length));let[o,...c]=s;o.length===0?r=c.map(B):n[B(o)]=c.map(B)}),r?V(n)?[r]:[r,n]:V(n)?void 0:n}var ce=(e,t,n,r,s=[],o=[],c=new Map)=>{let u=Te(e);if(!u){zt(e,s,t);let y=c.get(e);if(y)return r?{transformedValue:null}:y}if(!kt(e,n)){let y=oe(e,n),f=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return u||c.set(e,f),f}if(A(o,e))return{transformedValue:null};let l=oe(e,n),S=l?.value??e,d=g(S)?[]:{},w={};v(S,(y,f)=>{if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error(`Detected property ${f}. This is a prototype pollution risk, please remove it from your object.`);let T=ce(y,t,n,r,[...s,f],[...o,e],c);d[f]=T.transformedValue,g(T.annotations)?w[f]=T.annotations:E(T.annotations)&&v(T.annotations,(X,Y)=>{w[se(f)+"."+Y]=X})});let N=V(w)?{transformedValue:d,annotations:l?[l.type]:void 0}:{transformedValue:d,annotations:l?[l.type,w]:w};return u||c.set(e,N),N};function F(e){return Object.prototype.toString.call(e).slice(8,-1)}function pe(e){return F(e)==="Array"}function Be(e){if(F(e)!=="Object")return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function jt(e){return F(e)==="Null"}function Nt(e,t,n,r,s){return o=>e(o)||t(o)||!!n&&n(o)||!!r&&r(o)||!!s&&s(o)}function _t(e){return F(e)==="Undefined"}var jn=Nt(jt,_t);function Mt(e,t,n,r,s){let o={}.propertyIsEnumerable.call(r,t)?"enumerable":"nonenumerable";o==="enumerable"&&(e[t]=n),s&&o==="nonenumerable"&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function G(e,t={}){if(pe(e))return e.map(s=>G(s,t));if(!Be(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((s,o)=>{if(pe(t.props)&&!t.props.includes(o))return s;let c=e[o],u=G(c,t);return Mt(s,o,u,e,t.nonenumerable),s},{})}var p=class{constructor({dedupe:t=!1}={}){this.classRegistry=new L,this.symbolRegistry=new O(n=>n.description??""),this.customTransformerRegistry=new U,this.allowedErrorProps=[],this.dedupe=t}serialize(t){let n=new Map,r=ce(t,n,this,this.dedupe),s={json:r.transformedValue};r.annotations&&(s.meta={...s.meta,values:r.annotations});let o=Ve(n,this.dedupe);return o&&(s.meta={...s.meta,referentialEqualities:o}),s}deserialize(t){let{json:n,meta:r}=t,s=G(n);return r?.values&&(s=Le(s,r.values,this)),r?.referentialEqualities&&(s=Ue(s,r.referentialEqualities)),s}stringify(t){return JSON.stringify(this.serialize(t))}parse(t){return this.deserialize(JSON.parse(t))}registerClass(t,n){this.classRegistry.register(t,n)}registerSymbol(t,n){this.symbolRegistry.register(t,n)}registerCustom(t,n){this.customTransformerRegistry.register({name:n,...t})}allowErrorProps(...t){this.allowedErrorProps.push(...t)}};p.defaultInstance=new p;p.serialize=p.defaultInstance.serialize.bind(p.defaultInstance);p.deserialize=p.defaultInstance.deserialize.bind(p.defaultInstance);p.stringify=p.defaultInstance.stringify.bind(p.defaultInstance);p.parse=p.defaultInstance.parse.bind(p.defaultInstance);p.registerClass=p.defaultInstance.registerClass.bind(p.defaultInstance);p.registerSymbol=p.defaultInstance.registerSymbol.bind(p.defaultInstance);p.registerCustom=p.defaultInstance.registerCustom.bind(p.defaultInstance);p.allowErrorProps=p.defaultInstance.allowErrorProps.bind(p.defaultInstance);var Qn=p.serialize,Lt=p.deserialize,De=p.stringify,Fn=p.parse,Gn=p.registerClass,Hn=p.registerCustom,Kn=p.registerSymbol,$n=p.allowErrorProps;var i=require("zod"),Qe=e=>typeof e=="string"?e:De(e);var R=i.z.number().refine(e=>!Number.isNaN(Number(new Date(e))),{message:"Invalid timestamp"}),Ut=i.z.object({ts:R,model:i.z.string().nullable(),operation:i.z.string(),args:i.z.union([i.z.record(i.z.unknown()),i.z.array(i.z.unknown())]),latency:i.z.number(),error:i.z.string().nullable(),connect:i.z.union([i.z.number(),i.z.literal(!1)]),sql:i.z.string().nullable(),hash:i.z.string().optional()}),Xn=i.z.array(Ut),Vt=i.z.union([i.z.literal("read"),i.z.literal("write"),i.z.literal("unknown")]),Bt=i.z.object({ts:R,workspaceId:i.z.string(),recordingId:i.z.number(),userId:i.z.string(),kind:Vt,shape:i.z.string(),query:i.z.string(),queryArgsJson:i.z.string(),sql:i.z.string().nullable(),latency:i.z.number(),connect:i.z.number().nullable(),error:i.z.string().nullable()}),Yn=i.z.array(Bt),Dt=i.z.object({id:i.z.number(),queryGroupId:i.z.number(),query:i.z.string(),seenAt:R,error:i.z.string().nullable(),latencyMs:i.z.number(),connectMs:i.z.number().nullable()}),Jn=i.z.array(Dt),Qt=i.z.object({id:i.z.number(),pattern:i.z.string(),rawQuery:i.z.string().nullable(),lastSeen:R,count:i.z.number(),errorCount:i.z.number(),latencyAvg:i.z.number(),latencyMax:i.z.number(),latencyP50:i.z.number(),latencyP99:i.z.number()}),er=i.z.array(Qt),Ft=i.z.object({id:i.z.number(),queryGroupId:i.z.number(),query:i.z.string(),seenAt:R,error:i.z.string().nullable(),latencyMs:i.z.number(),connectMs:i.z.number().nullable()}),Gt=i.z.object({count:i.z.number(),errorCount:i.z.number(),latencyAvg:i.z.number(),latencyMax:i.z.number(),latencyP50:i.z.number(),latencyP99:i.z.number()}),tr=i.z.object({perPage:i.z.number(),cursor:i.z.number().nullable(),pattern:i.z.string(),rawQuery:i.z.string().nullable(),queries:i.z.array(Ft),metrics:Gt}),nr=i.z.object({schema:i.z.string(),protocol:i.z.string().optional(),provider:i.z.string().optional()}),rr=i.z.object({workspaceId:i.z.string(),userId:i.z.string(),schema:i.z.string(),hash:i.z.string(),provider:i.z.string().optional(),protocol:i.z.string().optional()}),sr=i.z.object({id:i.z.number(),name:i.z.string(),userId:i.z.string(),schemaHash:i.z.string().nullable(),startTimestamp:R,endTimestamp:R.nullable()}),Ht=i.z.object({id:i.z.number(),name:i.z.string(),userId:i.z.string()}),Kt=i.z.array(Ht),ir=i.z.object({recordings:Kt,active:i.z.number().nullable()}),or=i.z.object({workspaceId:i.z.string(),userId:i.z.string()}),ar=i.z.object({id:i.z.number(),name:i.z.string(),startTimestamp:R}),cr=i.z.union([i.z.object({active:i.z.literal(!1)}),i.z.object({active:i.z.literal(!0),recordingId:i.z.number(),workspaceId:i.z.string(),schemaHash:i.z.string().nullable().optional()})]),pr=i.z.object({userId:i.z.string(),recordingId:i.z.coerce.number(),workspaceId:i.z.string()}),Fe=i.z.object({workspaceId:i.z.string(),recordingId:i.z.number(),name:i.z.string().optional(),schemaHash:i.z.string().optional()}),ur=Fe.pick({workspaceId:!0,recordingId:!0,schemaHash:!0}).required(),lr=Fe.pick({workspaceId:!0,recordingId:!0,name:!0}).required(),fr=i.z.enum(["main","dev"]);function $t(e,t){let n;return async function(r,s,o){let c=new URL(r,e),u=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${t}`});n&&u.set("prisma-optimize-jwt",n);let l=await fetch(c,{method:s,headers:u,body:Qe(o)});if(!l.ok){let d=await l.clone().text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${l.status} ${l.statusText}: ${d}`)}let S=l.headers.get("prisma-optimize-jwt");return S&&(n=S),l}}function Ge(e,t){let n=$t(e,t);return{request:n,post:(r,s)=>n(r,"POST",s)}}var He=It(require("kleur"));var{bold:Wt,underline:Zt}=He.default;function Ke(e){let t="See your Optimize dashboard at:",n=t.length,r=`${Zt(Wt(e))}`,s=e.length,o=Math.max(n,s)+2;console.log("\u250C"+"\u2500".repeat(o)+"\u2510"),console.log("\u2502 "+t+" ".repeat(o-n-2)+" \u2502"),console.log("\u2502 "+r+" ".repeat(o-s-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(o)+"\u2518")}var Je=require("@opentelemetry/api"),et=require("@opentelemetry/context-async-hooks"),tt=require("@opentelemetry/instrumentation"),nt=require("@opentelemetry/resources"),rt=require("@opentelemetry/sdk-trace-base"),Z=require("@opentelemetry/semantic-conventions"),st=require("@prisma/instrumentation");async function $e(e,t){t.length>0&&await e.post("/ingest",t)}async function We(e,t){return await(await e.post("/schema",t)).text()}function I(e){return e[0]*1e3+e[1]/1e6}var a=require("zod");var q=require("zod"),H=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(t){this.treeShape=t.treeShape,this.sendTimeout=t.sendTimeout,this.sendInterval=t.sendInterval,this.collectedSpans=t.collectedSpans,this.collectedRootSpans=t.collectedRootSpans,this.onEnd=Xt(()=>void this.forceFlush(),this.sendInterval)}onStart(t){let{parentSpanId:n,name:r}=t,{spanId:s}=t.spanContext();if(!this.collectedSpans.includes(r))return this.cleanSpan(this.spans[s]);this.spans[s]&&this.spans[s].kind==="future"?Object.assign(this.spans[s],{kind:"present",value:t}):this.spans[s]={spanId:s,kind:"present",children:[],value:t,retries:0},this.collectedRootSpans.includes(r)&&(this.rootSpans[s]={...this.spans[s],done:!1},this.waitSpans[s]=this.spans[s]),n!==void 0&&(this.spans[n]?this.spans[n].children.push(this.spans[s]):(this.spans[n]={spanId:n,kind:"future",children:[this.spans[s]],retries:0},this.waitSpans[n]=this.spans[n]))}cleanSpan(t){if(t===void 0)return;let n=t.spanId;for(let r of t.children)this.cleanSpan(r);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(t)}async forceFlush(){await this.pendingSend;let t=Object.values(this.rootSpans).flatMap(n=>{if(n.done)return[];let r=this.treeShape.safeParse(n);return r.data?(n.done=!0,[{original:n,pruned:r.data}]):[]});t.length>0&&(this.pendingSend=this.onFlush(t).finally(()=>{t.forEach(({original:n})=>this.cleanSpan(n))}));for(let n of Object.values(this.waitSpans))++n.retries*this.sendInterval>this.sendTimeout&&this.cleanSpan(n)}async shutdown(){await this.forceFlush(),this.spans={},this.rootSpans={},this.waitSpans={}}onEnd(){}};function Xt(e,t){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||e(),t))}}var m={ended:q.z.literal(!0),_spanContext:q.z.custom(),spanContext:q.z.custom(),startTime:q.z.custom(),endTime:q.z.custom(),attributes:q.z.custom()};var Ze=a.z.object({value:a.z.object({name:a.z.literal("prisma:engine:db_query"),...m})}),Yt=a.z.object({value:a.z.object({name:a.z.literal("prisma:engine:itx_execute_single"),...m}),children:k([Ze])}),K=a.z.object({value:a.z.object({name:a.z.union([a.z.literal("prisma:engine"),a.z.literal("prisma:engine:query")]),...m}),children:k([Ze])}),Jt=a.z.object({value:a.z.object({name:a.z.union([a.z.literal("prisma:engine"),a.z.literal("prisma:engine:query")]),...m}),children:k([Yt])}),$=a.z.object({value:a.z.object({name:a.z.literal("prisma:client:connect"),...m})}),ue=a.z.object({value:a.z.object({name:a.z.literal("prisma:client:operation"),...m}),children:a.z.union([a.z.tuple([K]),a.z.tuple([$,K]),a.z.tuple([K,$])])}),le=a.z.object({value:a.z.object({name:a.z.literal("prisma:client:operation"),...m}),children:k([Jt])}),en=a.z.object({value:a.z.object({name:a.z.union([a.z.literal("prisma:engine:start_transaction"),a.z.literal("prisma:engine:commit_transaction")]),...m})}),fe=a.z.object({value:a.z.object({name:a.z.literal("prisma:client:operation"),...m}),children:a.z.array($)}),me=a.z.object({value:a.z.object({name:a.z.literal("prisma:client:transaction"),...m}),children:k([en,le,$])}),de=a.z.object({value:a.z.object({name:a.z.literal("prisma:client:transaction"),...m}),children:k([fe,K])}),Xe=a.z.union([ue,me,de]);function k(e){return a.z.array(a.z.any()).nonempty().superRefine((t,n)=>{e.every(s=>t.some(o=>s.safeParse(o).success))||n.addIssue({code:"custom",message:"Array does not contain all the required items"})})}var W=class extends H{requests={};errors={};schemaHash;resolvedSchemaHash;apiClient;schemaRequest;constructor(t){super({treeShape:Xe,sendTimeout:t.sendTimeout,sendInterval:t.sendInterval,collectedSpans:["prisma:client:transaction","prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:query","prisma:engine:db_query","prisma:engine:itx_execute_single","prisma:engine:start_transaction","prisma:engine:commit_transaction"],collectedRootSpans:["prisma:client:operation","prisma:client:transaction"]}),this.apiClient=t.apiClient,this.schemaRequest=t.schemaRequest}setRequest(t){this.requests[t.spanId]=t}setError(t){this.errors[t.spanId]=t}onClean({spanId:t}){delete this.requests[t],delete this.errors[t]}async onFlush(t){this.schemaHash??=We(this.apiClient,this.schemaRequest),this.resolvedSchemaHash??=await this.schemaHash;let n=t.flatMap(({pruned:r})=>tn(r,this));await $e(this.apiClient,n)}};function tn(e,t){return me.safeParse(e).success?nn(e,t):de.safeParse(e).success?rn(e,t):ue.safeParse(e).success?sn(e,t):[]}function nn(e,t){let n=[],r=e.children.filter(s=>le.safeParse(s).success);for(let s of r){if(ye({span:s,ip:t})===!1)continue;let o=an(s);n.push(z({ip:t,span:s,sql:o,connect:!1}))}if(n.length){let s=ge(e);n.unshift(z({ip:t,span:e,sql:null,connect:s}))}return n}function rn(e,t){let n=[],r=e.children.filter(o=>fe.safeParse(o).success),s=!1;for(let o of r)ye({span:o,ip:t})!==!1&&(s||=ge(o),n.push(z({ip:t,span:o,sql:null,connect:!1})));return n.length&&n.unshift(z({ip:t,span:e,sql:null,connect:s})),n}function sn(e,t){let n=ge(e),r=on(e);return ye({span:e,ip:t})===!1?[]:[z({ip:t,span:e,sql:r,connect:n})]}function z(e){let{span:t,sql:n,connect:r,ip:s}=e,o=t.value.spanContext().spanId,{value:c}=t;return{hash:s.resolvedSchemaHash,sql:n??null,connect:r??!1,error:s.errors[o]?.error??null,ts:I(c.startTime),model:s.requests[o]?.model??c.attributes.model??null,operation:s.requests[o]?.operation??c.attributes.method,args:s.requests[o]?.args??{},latency:I(c.endTime)-I(c.startTime)}}function Ye(e){return e.sort((n,r)=>I(n.value.startTime)-I(r.value.startTime)).reduce((n,r)=>{let s=r.value.attributes["db.statement"];return s??=r.value.attributes["db.query.text"],typeof s=="string"?`${n}${s}
2
- `:n},"")}function on(e){let{children:t}=e.children.find(({value:r})=>r.name==="prisma:engine"||r.name==="prisma:engine:query"),n=t.filter(({value:r})=>r.name==="prisma:engine:db_query");return Ye(n)}function an(e){let{children:t}=e.children.find(({value:s})=>s.name==="prisma:engine"||s.name==="prisma:engine:query"),r=t.filter(({value:s})=>s.name==="prisma:engine:itx_execute_single").flatMap(({children:s})=>s.filter(({value:o})=>o.name==="prisma:engine:db_query"));return Ye(r)}function ge(e){let{value:t}=e.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return t?I(t.endTime)-I(t.startTime):!1}function ye(e){let{span:t,ip:n}=e;return!!n.requests[t.value.spanContext().spanId]}var j;function it(e){if(j)return j;let t=new et.AsyncHooksContextManager().enable();Je.context.setGlobalContextManager(t);let n=new rt.BasicTracerProvider({resource:new nt.Resource({[Z.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[Z.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})});return j=new W(e),n.addSpanProcessor(j),(0,tt.registerInstrumentations)({tracerProvider:n,instrumentations:[new st.PrismaInstrumentation]}),n.register(),j}function ot(e){return e._previewFeatures?.includes("tracing")}function at(e){return e._engineConfig.inlineSchema}function ct(e){if(e instanceof Error)return e.stack??e.message;switch(typeof e){case"undefined":return"undefined";case"object":{let t;return e!==null&&typeof e.toString=="function"&&(t=e.toString()),typeof t=="string"&&t!=="[object Object]"?t:JSON.stringify(e)}default:return String(e)}}var pt=require("@prisma/client/extension"),ut=pt.Prisma.defineExtension(e=>e.$extends({}));var mt="https://optimize-ingestion.datacdn.workers.dev/",dt="https://optimize.prisma.io";function cn({enable:e=!0,ingestionUrl:t=mt,dashboardUrl:n=dt,sendInterval:r=500,sendTimeout:s=1e4,showNotification:o=!0,apiKey:c}){return e?(o&&Ke(n),ft.Prisma.defineExtension(u=>{let l=at(u),S=Reflect.get(u,"_activeProvider"),d=Reflect.get(u,"_accelerateEngineConfig"),{protocol:w}=new URL(d.accelerateUtils.resolveDatasourceUrl(d)),N={schema:l,provider:S,protocol:w},y=Ge(t,c),f=it({schemaRequest:N,apiClient:y,sendInterval:r,sendTimeout:s});if(!ot(u))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return u.$extends({query:{async $allOperations({query:T,model:X,operation:Y,args:he}){let J=lt.trace.getActiveSpan()?.spanContext().spanId;if(!J)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");f.setRequest({spanId:J,model:X,operation:Y,args:he});try{return await T(he)}catch(Se){let gt=ct(Se);throw f.setError({spanId:J,error:gt}),Se}}}})})):ut}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
1
+ "use strict";var dt=Object.create;var z=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,yt=Object.prototype.hasOwnProperty;var xt=(e,t)=>{for(var n in t)z(e,n,{get:t[n],enumerable:!0})},Se=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ht(t))!yt.call(e,s)&&s!==n&&z(e,s,{get:()=>t[s],enumerable:!(r=gt(t,s))||r.enumerable});return e};var bt=(e,t,n)=>(n=e!=null?dt(St(e)):{},Se(t||!e||!e.__esModule?z(n,"default",{value:e,enumerable:!0}):n,e)),Tt=e=>Se(z({},"__esModule",{value:!0}),e);var Xt={};xt(Xt,{PROD_DASHBOARD_URL:()=>ft,PROD_INGESTION_URL:()=>lt,withOptimize:()=>Zt});module.exports=Tt(Xt);var pt=require("@opentelemetry/api"),ut=require("@prisma/client/extension");var N=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(t,n){this.keyToValue.set(t,n),this.valueToKey.set(n,t)}getByKey(t){return this.keyToValue.get(t)}getByValue(t){return this.valueToKey.get(t)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}};var E=class{constructor(t){this.generateIdentifier=t,this.kv=new N}register(t,n){this.kv.getByValue(t)||(n||(n=this.generateIdentifier(t)),this.kv.set(n,t))}clear(){this.kv.clear()}getIdentifier(t){return this.kv.getByValue(t)}getValue(t){return this.kv.getByKey(t)}};var _=class extends E{constructor(){super(t=>t.name),this.classToAllowedProps=new Map}register(t,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(t,n.allowProps),super.register(t,n.identifier)):super.register(t,n)}getAllowedProps(t){return this.classToAllowedProps.get(t)}};function It(e){if("values"in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function ye(e,t){let n=It(e);if("find"in n)return n.find(t);let r=n;for(let s=0;s<r.length;s++){let i=r[s];if(t(i))return i}}function R(e,t){Object.entries(e).forEach(([n,r])=>t(r,n))}function O(e,t){return e.indexOf(t)!==-1}function Y(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var B=class{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return ye(this.transfomers,n=>n.isApplicable(t))}findByName(t){return this.transfomers[t]}};var Rt=e=>Object.prototype.toString.call(e).slice(8,-1),J=e=>typeof e>"u",wt=e=>e===null,w=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,V=e=>w(e)&&Object.keys(e).length===0,d=e=>Array.isArray(e),vt=e=>typeof e=="string",Et=e=>typeof e=="number"&&!isNaN(e),Ot=e=>typeof e=="boolean",xe=e=>e instanceof RegExp,y=e=>e instanceof Map,x=e=>e instanceof Set,ee=e=>Rt(e)==="Symbol",be=e=>e instanceof Date&&!isNaN(e.valueOf()),Te=e=>e instanceof Error,te=e=>typeof e=="number"&&isNaN(e),Ie=e=>Ot(e)||wt(e)||J(e)||Et(e)||vt(e)||ee(e),Re=e=>typeof e=="bigint",we=e=>e===1/0||e===-1/0,ve=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Ee=e=>e instanceof URL;var ne=e=>e.replace(/\./g,"\\."),F=e=>e.map(String).map(ne).join("."),P=e=>{let t=[],n="";for(let s=0;s<e.length;s++){let i=e.charAt(s);if(i==="\\"&&e.charAt(s+1)==="."){n+=".",s++;continue}if(i==="."){t.push(n),n="";continue}n+=i}let r=n;return t.push(r),t};function h(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Oe=[h(J,"undefined",()=>null,()=>{}),h(Re,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),h(be,"Date",e=>e.toISOString(),e=>new Date(e)),h(Te,"Error",(e,t)=>{let n={name:e.name,message:e.message};return t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n},(e,t)=>{let n=new Error(e.message);return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(r=>{n[r]=e[r]}),n}),h(xe,"regexp",e=>""+e,e=>{let t=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,n)}),h(x,"set",e=>[...e.values()],e=>new Set(e)),h(y,"map",e=>[...e.entries()],e=>new Map(e)),h(e=>te(e)||we(e),"number",e=>te(e)?"NaN":e>0?"Infinity":"-Infinity",Number),h(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),h(Ee,"URL",e=>e.toString(),e=>new URL(e))];function M(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var Pe=M((e,t)=>ee(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw new Error("Trying to deserialize unknown symbol");return r}),Pt=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),Ae=M(ve,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{let n=Pt[t[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function re(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var qe=M(re,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(s=>{r[s]=e[s]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),Ce=M((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw new Error("Trying to deserialize unknown custom value");return r.deserialize(e)}),At=[qe,Pe,Ce,Ae],se=(e,t)=>{let n=Y(At,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=Y(Oe,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},ke={};Oe.forEach(e=>{ke[e.annotation]=e});var je=(e,t,n)=>{if(d(t))switch(t[0]){case"symbol":return Pe.untransform(e,t,n);case"class":return qe.untransform(e,t,n);case"custom":return Ce.untransform(e,t,n);case"typed-array":return Ae.untransform(e,t,n);default:throw new Error("Unknown transformation: "+t)}else{let r=ke[t];if(!r)throw new Error("Unknown transformation: "+t);return r.untransform(e,n)}};var A=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function ze(e){if(O(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(O(e,"prototype"))throw new Error("prototype is not allowed as a property");if(O(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Ne=(e,t)=>{ze(t);for(let n=0;n<t.length;n++){let r=t[n];if(x(e))e=A(e,+r);else if(y(e)){let s=+r,i=+t[++n]==0?"key":"value",a=A(e,s);switch(i){case"key":e=a;break;case"value":e=e.get(a);break}}else e=e[r]}return e},U=(e,t,n)=>{if(ze(t),t.length===0)return n(e);let r=e;for(let i=0;i<t.length-1;i++){let a=t[i];if(d(r)){let p=+a;r=r[p]}else if(w(r))r=r[a];else if(x(r)){let p=+a;r=A(r,p)}else if(y(r)){if(i===t.length-2)break;let u=+a,S=+t[++i]==0?"key":"value",m=A(r,u);switch(S){case"key":r=m;break;case"value":r=r.get(m);break}}}let s=t[t.length-1];if(d(r)?r[+s]=n(r[+s]):w(r)&&(r[s]=n(r[s])),x(r)){let i=A(r,+s),a=n(i);i!==a&&(r.delete(i),r.add(a))}if(y(r)){let i=+t[t.length-2],a=A(r,i);switch(+s==0?"key":"value"){case"key":{let u=n(a);r.set(u,r.get(a)),u!==a&&r.delete(a);break}case"value":{r.set(a,n(r.get(a)));break}}}return e};function ie(e,t,n=[]){if(!e)return;if(!d(e)){R(e,(i,a)=>ie(i,t,[...n,...P(a)]));return}let[r,s]=e;s&&R(s,(i,a)=>{ie(i,t,[...n,...P(a)])}),t(r,n)}function _e(e,t,n){return ie(t,(r,s)=>{e=U(e,s,i=>je(i,r,n))}),e}function Be(e,t){function n(r,s){let i=Ne(e,P(s));r.map(P).forEach(a=>{e=U(e,a,()=>i)})}if(d(t)){let[r,s]=t;r.forEach(i=>{e=U(e,P(i),()=>e)}),s&&R(s,n)}else R(t,n);return e}var qt=(e,t)=>w(e)||d(e)||y(e)||x(e)||re(e,t);function Ct(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function Ve(e,t){let n={},r;return e.forEach(s=>{if(s.length<=1)return;t||(s=s.map(p=>p.map(String)).sort((p,u)=>p.length-u.length));let[i,...a]=s;i.length===0?r=a.map(F):n[F(i)]=a.map(F)}),r?V(n)?[r]:[r,n]:V(n)?void 0:n}var oe=(e,t,n,r,s=[],i=[],a=new Map)=>{let p=Ie(e);if(!p){Ct(e,s,t);let g=a.get(e);if(g)return r?{transformedValue:null}:g}if(!qt(e,n)){let g=se(e,n),l=g?{transformedValue:g.value,annotations:[g.type]}:{transformedValue:e};return p||a.set(e,l),l}if(O(i,e))return{transformedValue:null};let u=se(e,n),S=u?.value??e,m=d(S)?[]:{},T={};R(S,(g,l)=>{if(l==="__proto__"||l==="constructor"||l==="prototype")throw new Error(`Detected property ${l}. This is a prototype pollution risk, please remove it from your object.`);let I=oe(g,t,n,r,[...s,l],[...i,e],a);m[l]=I.transformedValue,d(I.annotations)?T[l]=I.annotations:w(I.annotations)&&R(I.annotations,(G,Z)=>{T[ne(l)+"."+Z]=G})});let j=V(T)?{transformedValue:m,annotations:u?[u.type]:void 0}:{transformedValue:m,annotations:u?[u.type,T]:T};return p||a.set(e,j),j};function D(e){return Object.prototype.toString.call(e).slice(8,-1)}function ae(e){return D(e)==="Array"}function Fe(e){if(D(e)!=="Object")return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function kt(e){return D(e)==="Null"}function jt(e,t,n,r,s){return i=>e(i)||t(i)||!!n&&n(i)||!!r&&r(i)||!!s&&s(i)}function zt(e){return D(e)==="Undefined"}var Rn=jt(kt,zt);function Nt(e,t,n,r,s){let i={}.propertyIsEnumerable.call(r,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=n),s&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function L(e,t={}){if(ae(e))return e.map(s=>L(s,t));if(!Fe(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((s,i)=>{if(ae(t.props)&&!t.props.includes(i))return s;let a=e[i],p=L(a,t);return Nt(s,i,p,e,t.nonenumerable),s},{})}var c=class{constructor({dedupe:t=!1}={}){this.classRegistry=new _,this.symbolRegistry=new E(n=>n.description??""),this.customTransformerRegistry=new B,this.allowedErrorProps=[],this.dedupe=t}serialize(t){let n=new Map,r=oe(t,n,this,this.dedupe),s={json:r.transformedValue};r.annotations&&(s.meta={...s.meta,values:r.annotations});let i=Ve(n,this.dedupe);return i&&(s.meta={...s.meta,referentialEqualities:i}),s}deserialize(t){let{json:n,meta:r}=t,s=L(n);return r?.values&&(s=_e(s,r.values,this)),r?.referentialEqualities&&(s=Be(s,r.referentialEqualities)),s}stringify(t){return JSON.stringify(this.serialize(t))}parse(t){return this.deserialize(JSON.parse(t))}registerClass(t,n){this.classRegistry.register(t,n)}registerSymbol(t,n){this.symbolRegistry.register(t,n)}registerCustom(t,n){this.customTransformerRegistry.register({name:n,...t})}allowErrorProps(...t){this.allowedErrorProps.push(...t)}};c.defaultInstance=new c;c.serialize=c.defaultInstance.serialize.bind(c.defaultInstance);c.deserialize=c.defaultInstance.deserialize.bind(c.defaultInstance);c.stringify=c.defaultInstance.stringify.bind(c.defaultInstance);c.parse=c.defaultInstance.parse.bind(c.defaultInstance);c.registerClass=c.defaultInstance.registerClass.bind(c.defaultInstance);c.registerSymbol=c.defaultInstance.registerSymbol.bind(c.defaultInstance);c.registerCustom=c.defaultInstance.registerCustom.bind(c.defaultInstance);c.allowErrorProps=c.defaultInstance.allowErrorProps.bind(c.defaultInstance);var kn=c.serialize,_t=c.deserialize,Me=c.stringify,jn=c.parse,zn=c.registerClass,Ue=c.registerCustom,Nn=c.registerSymbol,_n=c.allowErrorProps;Ue({isApplicable:e=>typeof Buffer<"u"&&e instanceof Buffer,serialize:e=>[...e],deserialize:e=>typeof Buffer<"u"?Buffer.from(e):new Float32Array(e)},"buffer");var De=e=>typeof e=="string"?e:Me(e);function Bt(e,t){let n;return async function(r,s,i){let a=new URL(r,e),p=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${t}`});n&&p.set("prisma-optimize-jwt",n);let u=await fetch(a,{method:s,headers:p,body:De(i)});if(!u.ok){let m=await u.clone().text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${u.status} ${u.statusText}: ${m}`)}let S=u.headers.get("prisma-optimize-jwt");return S&&(n=S),u}}function Le(e,t){let n=Bt(e,t);return{request:n,post:(r,s)=>n(r,"POST",s)}}var $e=bt(require("kleur"));var{bold:Vt,underline:Ft}=$e.default;function He(e){let t="See your Optimize dashboard at:",n=t.length,r=`${Ft(Vt(e))}`,s=e.length,i=Math.max(n,s)+2;console.log("\u250C"+"\u2500".repeat(i)+"\u2510"),console.log("\u2502 "+t+" ".repeat(i-n-2)+" \u2502"),console.log("\u2502 "+r+" ".repeat(i-s-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(i)+"\u2518")}var Xe=require("@opentelemetry/api"),Ye=require("@opentelemetry/context-async-hooks"),Je=require("@opentelemetry/instrumentation"),et=require("@opentelemetry/resources"),tt=require("@opentelemetry/sdk-trace-base"),W=require("@opentelemetry/semantic-conventions"),nt=require("@prisma/instrumentation");async function Ke(e,t){t.length>0&&await e.post("/ingest",t)}async function Qe(e,t){return await(await e.post("/schema",t)).text()}function b(e){return e[0]*1e3+e[1]/1e6}var o=require("zod");var v=require("zod"),$=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(t){this.treeShape=t.treeShape,this.sendTimeout=t.sendTimeout,this.sendInterval=t.sendInterval,this.collectedSpans=t.collectedSpans,this.collectedRootSpans=t.collectedRootSpans,this.onEnd=Mt(()=>void this.forceFlush(),this.sendInterval)}onStart(t){let{parentSpanId:n,name:r}=t,{spanId:s}=t.spanContext();if(!this.collectedSpans.includes(r))return this.cleanSpan(this.spans[s]);this.spans[s]&&this.spans[s].kind==="future"?Object.assign(this.spans[s],{kind:"present",value:t}):this.spans[s]={spanId:s,kind:"present",children:[],value:t,retries:0},this.collectedRootSpans.includes(r)&&(this.rootSpans[s]={...this.spans[s],done:!1},this.waitSpans[s]=this.spans[s]),n!==void 0&&(this.spans[n]?this.spans[n].children.push(this.spans[s]):(this.spans[n]={spanId:n,kind:"future",children:[this.spans[s]],retries:0},this.waitSpans[n]=this.spans[n]))}cleanSpan(t){if(t===void 0)return;let n=t.spanId;for(let r of t.children)this.cleanSpan(r);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(t)}async forceFlush(){await this.pendingSend;let t=Object.values(this.rootSpans).flatMap(n=>{if(n.done)return[];let r=this.treeShape.safeParse(n);return r.data?(n.done=!0,[{original:n,pruned:r.data}]):[]});t.length>0&&(this.pendingSend=this.onFlush(t).finally(()=>{t.forEach(({original:n})=>this.cleanSpan(n))}));for(let n of Object.values(this.waitSpans))++n.retries*this.sendInterval>this.sendTimeout&&this.cleanSpan(n)}async shutdown(){await this.forceFlush(),this.spans={},this.rootSpans={},this.waitSpans={}}onEnd(){}};function Mt(e,t){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||e(),t))}}var f={ended:v.z.literal(!0),_spanContext:v.z.custom(),spanContext:v.z.custom(),startTime:v.z.custom(),endTime:v.z.custom(),attributes:v.z.custom()};var We=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:db_query"),...f})}),Ut=o.z.object({value:o.z.object({name:o.z.literal("prisma:engine:itx_execute_single"),...f}),children:q([We])}),H=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine"),o.z.literal("prisma:engine:query")]),...f}),children:q([We])}),Dt=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine"),o.z.literal("prisma:engine:query")]),...f}),children:q([Ut])}),K=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:connect"),...f})}),ce=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:o.z.union([o.z.tuple([H]),o.z.tuple([K,H]),o.z.tuple([H,K])])}),pe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:q([Dt])}),Lt=o.z.object({value:o.z.object({name:o.z.union([o.z.literal("prisma:engine:start_transaction"),o.z.literal("prisma:engine:commit_transaction")]),...f})}),ue=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:operation"),...f}),children:o.z.array(K)}),le=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([Lt,pe,K])}),fe=o.z.object({value:o.z.object({name:o.z.literal("prisma:client:transaction"),...f}),children:q([ue,H])}),Ge=o.z.union([ce,le,fe]);function q(e){return o.z.array(o.z.any()).nonempty().superRefine((t,n)=>{e.every(s=>t.some(i=>s.safeParse(i).success))||n.addIssue({code:"custom",message:"Array does not contain all the required items"})})}var Q=class extends ${requests={};errors={};schemaHash;resolvedSchemaHash;apiClient;schemaRequest;constructor(t){super({treeShape:Ge,sendTimeout:t.sendTimeout,sendInterval:t.sendInterval,collectedSpans:["prisma:client:transaction","prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:query","prisma:engine:db_query","prisma:engine:itx_execute_single","prisma:engine:start_transaction","prisma:engine:commit_transaction"],collectedRootSpans:["prisma:client:operation","prisma:client:transaction"]}),this.apiClient=t.apiClient,this.schemaRequest=t.schemaRequest}setRequest(t){this.requests[t.spanId]=t}setError(t){this.errors[t.spanId]=t}onClean({spanId:t}){delete this.requests[t],delete this.errors[t]}async onFlush(t){this.schemaHash??=Qe(this.apiClient,this.schemaRequest),this.resolvedSchemaHash??=await this.schemaHash;let n=t.flatMap(({pruned:r})=>$t(r,this));await Ke(this.apiClient,n)}};function $t(e,t){return le.safeParse(e).success?Ht(e,t):fe.safeParse(e).success?Kt(e,t):ce.safeParse(e).success?Qt(e,t):[]}function Ht(e,t){let n=[],r=e.children.filter(s=>pe.safeParse(s).success);for(let s of r){if(de({span:s,ip:t})===!1)continue;let i=Gt(s);n.push(C({ip:t,span:s,sql:i,connect:!1}))}if(n.length){let s=me(e);n.unshift(C({ip:t,span:e,sql:null,connect:s}))}return n}function Kt(e,t){let n=[],r=e.children.filter(i=>ue.safeParse(i).success),s=!1;for(let i of r)de({span:i,ip:t})!==!1&&(s||=me(i),n.push(C({ip:t,span:i,sql:null,connect:!1})));return n.length&&n.unshift(C({ip:t,span:e,sql:null,connect:s})),n}function Qt(e,t){let n=me(e),r=Wt(e);return de({span:e,ip:t})===!1?[]:[C({ip:t,span:e,sql:r,connect:n})]}function C(e){let{span:t,sql:n,connect:r,ip:s}=e,i=t.value.spanContext().spanId,{value:a}=t;return{hash:s.resolvedSchemaHash,sql:n??null,connect:r??!1,error:s.errors[i]?.error??null,ts:b(a.startTime),model:s.requests[i]?.model??a.attributes.model??null,operation:s.requests[i]?.operation??a.attributes.method,args:s.requests[i]?.args??{},latency:b(a.endTime)-b(a.startTime)}}function Ze(e){return e.sort((n,r)=>b(n.value.startTime)-b(r.value.startTime)).reduce((n,r)=>{let s=r.value.attributes["db.statement"];return s??=r.value.attributes["db.query.text"],typeof s=="string"?`${n}${s}
2
+ `:n},"")}function Wt(e){let{children:t}=e.children.find(({value:r})=>r.name==="prisma:engine"||r.name==="prisma:engine:query"),n=t.filter(({value:r})=>r.name==="prisma:engine:db_query");return Ze(n)}function Gt(e){let{children:t}=e.children.find(({value:s})=>s.name==="prisma:engine"||s.name==="prisma:engine:query"),r=t.filter(({value:s})=>s.name==="prisma:engine:itx_execute_single").flatMap(({children:s})=>s.filter(({value:i})=>i.name==="prisma:engine:db_query"));return Ze(r)}function me(e){let{value:t}=e.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return t?b(t.endTime)-b(t.startTime):!1}function de(e){let{span:t,ip:n}=e;return!!n.requests[t.value.spanContext().spanId]}var k;function rt(e){if(k)return k;let t=new Ye.AsyncHooksContextManager().enable();Xe.context.setGlobalContextManager(t);let n=new tt.BasicTracerProvider({resource:new et.Resource({[W.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[W.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})});return k=new Q(e),n.addSpanProcessor(k),(0,Je.registerInstrumentations)({tracerProvider:n,instrumentations:[new nt.PrismaInstrumentation]}),n.register(),k}function st(e){return e._previewFeatures?.includes("tracing")}function it(e){return e._engineConfig.inlineSchema}function ot(e){if(e instanceof Error)return e.stack??e.message;switch(typeof e){case"undefined":return"undefined";case"object":{let t;return e!==null&&typeof e.toString=="function"&&(t=e.toString()),typeof t=="string"&&t!=="[object Object]"?t:JSON.stringify(e)}default:return String(e)}}var at=require("@prisma/client/extension"),ct=at.Prisma.defineExtension(e=>e.$extends({}));var lt="https://optimize-ingestion.datacdn.workers.dev/",ft="https://optimize.prisma.io";function Zt({enable:e=!0,ingestionUrl:t=lt,dashboardUrl:n=ft,sendInterval:r=500,sendTimeout:s=1e4,showNotification:i=!0,apiKey:a}){return e?(i&&He(n),ut.Prisma.defineExtension(p=>{let u=it(p),S=Reflect.get(p,"_activeProvider"),m=Reflect.get(p,"_accelerateEngineConfig"),{protocol:T}=new URL(m.accelerateUtils.resolveDatasourceUrl(m)),j={schema:u,provider:S,protocol:T},g=Le(t,a),l=rt({schemaRequest:j,apiClient:g,sendInterval:r,sendTimeout:s});if(!st(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return p.$extends({query:{async $allOperations({query:I,model:G,operation:Z,args:ge}){let X=pt.trace.getActiveSpan()?.spanContext().spanId;if(!X)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");l.setRequest({spanId:X,model:G,operation:Z,args:ge});try{return await I(ge)}catch(he){let mt=ot(he);throw l.setError({spanId:X,error:mt}),he}}}})})):ct}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/extension-optimize",
3
- "version": "0.0.0-dev.202412312046",
3
+ "version": "0.0.0-dev.202501011234",
4
4
  "sideEffects": false,
5
5
  "description": "",
6
6
  "main": "./dist/index.js",
@@ -17,7 +17,7 @@
17
17
  "@prisma/instrumentation": "5.19.1",
18
18
  "kleur": "4.1.5",
19
19
  "zod": "3.23.8",
20
- "common": "0.0.0-dev.202412312046"
20
+ "common": "0.0.0-dev.202501011234"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@hono/node-server": "1.9.1",