@prisma/extension-optimize 1.0.0 → 1.0.2

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 +5 -5
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Z=Object.create;var f=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var te=(t,e)=>{for(var n in e)f(t,n,{get:e[n],enumerable:!0})},C=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of X(e))!ee.call(t,r)&&r!==n&&f(t,r,{get:()=>e[r],enumerable:!(s=W(e,r))||s.enumerable});return t};var ne=(t,e,n)=>(n=t!=null?Z(Y(t)):{},C(e||!t||!t.__esModule?f(n,"default",{value:t,enumerable:!0}):n,t)),re=t=>C(f({},"__esModule",{value:!0}),t);var ue={};te(ue,{PROD_DASHBOARD_URL:()=>Q,PROD_INGESTION_URL:()=>J,withOptimize:()=>de});module.exports=re(ue);var N=require("@opentelemetry/api"),D=require("@prisma/client/extension");function se(t,e){let n;return async function(s,r,o){let a=new URL(s,t),m=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});n&&m.set("prisma-optimize-jwt",n);let p=await fetch(a,{method:r,headers:m,body:JSON.stringify(o)});if(!p.ok){let h=await p.text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${p.status} ${p.statusText}: ${h}`)}let u=p.headers.get("prisma-optimize-jwt");return u&&(n=u),p}}function w(t,e){let n=se(t,e);return{request:n,post:(s,r)=>n(s,"POST",r)}}var v=ne(require("kleur"));var{bold:ie,underline:oe}=v.default;function R(t){let e="See your Optimize dashboard at:",n=e.length,s=`${oe(ie(t))}`,r=t.length,o=Math.max(n,r)+2;console.log("\u250C"+"\u2500".repeat(o)+"\u2510"),console.log("\u2502 "+e+" ".repeat(o-n-2)+" \u2502"),console.log("\u2502 "+s+" ".repeat(o-r-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(o)+"\u2518")}var q=require("@opentelemetry/api"),O=require("@opentelemetry/context-async-hooks"),j=require("@opentelemetry/instrumentation"),_=require("@opentelemetry/resources"),z=require("@opentelemetry/sdk-trace-base"),b=require("@opentelemetry/semantic-conventions"),k=require("@prisma/instrumentation");var i=require("zod");async function P(t,e){e.length>0&&await t.post("/ingest",e)}async function E(t,e){return await(await t.post("/schema",{schema:e})).text()}function c(t){return t[0]*1e3+t[1]/1e6}var l=require("zod"),S=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(e){this.treeShape=e.treeShape,this.sendTimeout=e.sendTimeout,this.sendInterval=e.sendInterval,this.collectedSpans=e.collectedSpans,this.collectedRootSpans=e.collectedRootSpans,this.onEnd=ae(()=>void this.forceFlush(),this.sendInterval)}onStart(e){let{parentSpanId:n,name:s}=e,{spanId:r}=e.spanContext();if(!this.collectedSpans.includes(s))return this.cleanSpan(this.spans[r]);this.spans[r]&&this.spans[r].kind==="future"?Object.assign(this.spans[r],{kind:"present",value:e}):this.spans[r]={spanId:r,kind:"present",children:[],value:e,retries:0},this.collectedRootSpans.includes(s)&&(this.rootSpans[r]={...this.spans[r],done:!1},this.waitSpans[r]=this.spans[r]),n!==void 0&&(this.spans[n]?this.spans[n].children.push(this.spans[r]):(this.spans[n]={spanId:n,kind:"future",children:[this.spans[r]],retries:0},this.waitSpans[n]=this.spans[n]))}cleanSpan(e){if(e===void 0)return;let n=e.spanId;for(let s of e.children)this.cleanSpan(s);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(e)}async forceFlush(){await this.pendingSend;let e=Object.values(this.rootSpans).flatMap(n=>{if(n.done)return[];let{data:s}=this.treeShape.safeParse(n);return s?(n.done=!0,[{original:n,pruned:s}]):[]});e.length>0&&(this.pendingSend=this.onFlush(e).finally(()=>{e.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 ae(t,e){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||t(),e))}}var d={ended:l.z.literal(!0),_spanContext:l.z.custom(),spanContext:l.z.custom(),startTime:l.z.custom(),endTime:l.z.custom(),attributes:l.z.custom()};var pe=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine:db_query"),...d})}),y=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine"),...d}),children:i.z.array(pe).nonempty()}),A=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:connect"),...d})}),ce=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:operation"),...d}),children:i.z.union([i.z.tuple([y]),i.z.tuple([A,y]),i.z.tuple([y,A])])}),g=class extends S{requests={};errors={};schemaHash;apiClient;constructor(e){super({treeShape:ce,sendTimeout:e.sendTimeout,sendInterval:e.sendInterval,collectedSpans:["prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:db_query"],collectedRootSpans:["prisma:client:operation"]}),this.apiClient=e.apiClient,this.schemaHash=E(this.apiClient,e.schema)}setRequest(e){this.requests[e.spanId]=e}setError(e){this.errors[e.spanId]=e}onClean({spanId:e}){delete this.requests[e],delete this.errors[e]}async onFlush(e){let n=await this.schemaHash,s=[];for(let{pruned:r}of e){let{value:o}=r,a=o.spanContext().spanId;this.requests[a]&&s.push({hash:n,sql:le(r),ts:c(o.startTime),connect:me(r),error:this.errors[a]?.error??null,model:this.requests[a].model??null,operation:this.requests[a].operation,args:this.requests[a].args??{},latency:c(o.endTime)-c(o.startTime)})}await P(this.apiClient,s)}};function le(t){return t.children.find(({value:r})=>r.name==="prisma:engine").children.filter(({value:r})=>r.name==="prisma:engine:db_query").sort((r,o)=>c(r.value.startTime)-c(o.value.startTime)).reduce((r,o)=>{let a=o.value.attributes["db.statement"];return typeof a=="string"?`${r}${a}
2
- `:r},"")}function me(t){let{value:e}=t.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return e?c(e.endTime)-c(e.startTime):!1}function F(t){let e=new O.AsyncHooksContextManager().enable();q.context.setGlobalContextManager(e);let n=new z.BasicTracerProvider({resource:new _.Resource({[b.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[b.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),s=new g(t);return n.addSpanProcessor(s),(0,j.registerInstrumentations)({tracerProvider:n,instrumentations:[new k.PrismaInstrumentation]}),n.register(),s}function M(t){return t._previewFeatures?.includes("tracing")}function H(t){return t._engineConfig.inlineSchema}function L(t){if(t instanceof Error)return t.stack??t.message;switch(typeof t){case"undefined":return"undefined";case"object":{let e;return t!==null&&typeof t.toString=="function"&&(e=t.toString()),typeof e=="string"&&e!=="[object Object]"?e:JSON.stringify(t)}default:return String(t)}}var $=require("@prisma/client/extension"),U=$.Prisma.defineExtension(t=>t.$extends({}));var J="https://optimize-ingestion.datacdn.workers.dev/",Q="https://optimize.prisma.io";function de({enable:t=!0,ingestionUrl:e=J,dashboardUrl:n=Q,sendInterval:s=500,sendTimeout:r=1e4,showNotification:o=!0,apiKey:a}){return t?(o&&R(n),D.Prisma.defineExtension(m=>{let p=H(m),u=w(e,a),h=F({schema:p,apiClient:u,sendInterval:s,sendTimeout:r});if(!M(m))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return m.$extends({query:{async $allOperations({query:V,model:B,operation:G,args:x}){let T=N.trace.getActiveSpan()?.spanContext().spanId;if(!T)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");h.setRequest({spanId:T,model:B,operation:G,args:x});try{return await V(x)}catch(I){let K=L(I);throw h.setError({spanId:T,error:K}),I}}}})})):U}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
1
+ "use strict";var Y=Object.create;var S=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var ne=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty;var re=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},v=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of te(e))!se.call(t,s)&&s!==n&&S(t,s,{get:()=>e[s],enumerable:!(r=ee(e,s))||r.enumerable});return t};var ie=(t,e,n)=>(n=t!=null?Y(ne(t)):{},v(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),oe=t=>v(S({},"__esModule",{value:!0}),t);var fe={};re(fe,{PROD_DASHBOARD_URL:()=>B,PROD_INGESTION_URL:()=>V,withOptimize:()=>Se});module.exports=oe(fe);var J=require("@opentelemetry/api"),Q=require("@prisma/client/extension");function ae(t,e){let n;return async function(r,s,o){let a=new URL(r,t),l=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});n&&l.set("prisma-optimize-jwt",n);let p=await fetch(a,{method:s,headers:l,body:JSON.stringify(o)});if(!p.ok){let T=await p.text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${p.status} ${p.statusText}: ${T}`)}let h=p.headers.get("prisma-optimize-jwt");return h&&(n=h),p}}function w(t,e){let n=ae(t,e);return{request:n,post:(r,s)=>n(r,"POST",s)}}var q=ie(require("kleur"));var{bold:pe,underline:ce}=q.default;function P(t){let e="See your Optimize dashboard at:",n=e.length,r=`${ce(pe(t))}`,s=t.length,o=Math.max(n,s)+2;console.log("\u250C"+"\u2500".repeat(o)+"\u2510"),console.log("\u2502 "+e+" ".repeat(o-n-2)+" \u2502"),console.log("\u2502 "+r+" ".repeat(o-s-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(o)+"\u2518")}var j=require("@opentelemetry/api"),_=require("@opentelemetry/context-async-hooks"),z=require("@opentelemetry/instrumentation"),k=require("@opentelemetry/resources"),F=require("@opentelemetry/sdk-trace-base"),b=require("@opentelemetry/semantic-conventions"),M=require("@prisma/instrumentation");var i=require("zod");async function E(t,e){e.length>0&&await t.post("/ingest",e)}async function A(t,e){return await(await t.post("/schema",e)).text()}function c(t){return t[0]*1e3+t[1]/1e6}var m=require("zod"),f=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(e){this.treeShape=e.treeShape,this.sendTimeout=e.sendTimeout,this.sendInterval=e.sendInterval,this.collectedSpans=e.collectedSpans,this.collectedRootSpans=e.collectedRootSpans,this.onEnd=le(()=>void this.forceFlush(),this.sendInterval)}onStart(e){let{parentSpanId:n,name:r}=e,{spanId:s}=e.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:e}):this.spans[s]={spanId:s,kind:"present",children:[],value:e,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(e){if(e===void 0)return;let n=e.spanId;for(let r of e.children)this.cleanSpan(r);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(e)}async forceFlush(){await this.pendingSend;let e=Object.values(this.rootSpans).flatMap(n=>{if(n.done)return[];let{data:r}=this.treeShape.safeParse(n);return r?(n.done=!0,[{original:n,pruned:r}]):[]});e.length>0&&(this.pendingSend=this.onFlush(e).finally(()=>{e.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 le(t,e){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||t(),e))}}var u={ended:m.z.literal(!0),_spanContext:m.z.custom(),spanContext:m.z.custom(),startTime:m.z.custom(),endTime:m.z.custom(),attributes:m.z.custom()};var me=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine:db_query"),...u})}),I=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine"),...u}),children:i.z.array(me).nonempty()}),O=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:connect"),...u})}),ue=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:operation"),...u}),children:i.z.union([i.z.tuple([I]),i.z.tuple([O,I]),i.z.tuple([I,O])])}),g=class extends f{requests={};errors={};schemaHash;apiClient;constructor(e){super({treeShape:ue,sendTimeout:e.sendTimeout,sendInterval:e.sendInterval,collectedSpans:["prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:db_query"],collectedRootSpans:["prisma:client:operation"]}),this.apiClient=e.apiClient,this.schemaHash=A(this.apiClient,e.schemaRequest)}setRequest(e){this.requests[e.spanId]=e}setError(e){this.errors[e.spanId]=e}onClean({spanId:e}){delete this.requests[e],delete this.errors[e]}async onFlush(e){let n=await this.schemaHash,r=[];for(let{pruned:s}of e){let{value:o}=s,a=o.spanContext().spanId;this.requests[a]&&r.push({hash:n,sql:de(s),ts:c(o.startTime),connect:he(s),error:this.errors[a]?.error??null,model:this.requests[a].model??null,operation:this.requests[a].operation,args:this.requests[a].args??{},latency:c(o.endTime)-c(o.startTime)})}await E(this.apiClient,r)}};function de(t){return t.children.find(({value:s})=>s.name==="prisma:engine").children.filter(({value:s})=>s.name==="prisma:engine:db_query").sort((s,o)=>c(s.value.startTime)-c(o.value.startTime)).reduce((s,o)=>{let a=o.value.attributes["db.statement"];return typeof a=="string"?`${s}${a}
2
+ `:s},"")}function he(t){let{value:e}=t.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return e?c(e.endTime)-c(e.startTime):!1}var d;function H(t){if(d)return d;let e=new _.AsyncHooksContextManager().enable();j.context.setGlobalContextManager(e);let n=new F.BasicTracerProvider({resource:new k.Resource({[b.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[b.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})});return d=new g(t),n.addSpanProcessor(d),(0,z.registerInstrumentations)({tracerProvider:n,instrumentations:[new M.PrismaInstrumentation]}),n.register(),d}function L(t){return t._previewFeatures?.includes("tracing")}function $(t){return t._engineConfig.inlineSchema}function N(t){if(t instanceof Error)return t.stack??t.message;switch(typeof t){case"undefined":return"undefined";case"object":{let e;return t!==null&&typeof t.toString=="function"&&(e=t.toString()),typeof e=="string"&&e!=="[object Object]"?e:JSON.stringify(t)}default:return String(t)}}var U=require("@prisma/client/extension"),D=U.Prisma.defineExtension(t=>t.$extends({}));var V="https://optimize-ingestion.datacdn.workers.dev/",B="https://optimize.prisma.io";function Se({enable:t=!0,ingestionUrl:e=V,dashboardUrl:n=B,sendInterval:r=500,sendTimeout:s=1e4,showNotification:o=!0,apiKey:a}){return t?(o&&P(n),Q.Prisma.defineExtension(l=>{let p=$(l),h=Reflect.get(l,"_activeProvider"),T={schema:p,provider:h},G=w(e,a),x=H({schemaRequest:T,apiClient:G,sendInterval:r,sendTimeout:s});if(!L(l))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return l.$extends({query:{async $allOperations({query:K,model:Z,operation:W,args:R}){let y=J.trace.getActiveSpan()?.spanContext().spanId;if(!y)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");x.setRequest({spanId:y,model:Z,operation:W,args:R});try{return await K(R)}catch(C){let X=N(C);throw x.setError({spanId:y,error:X}),C}}}})})):D}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@prisma/extension-optimize",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "sideEffects": false,
5
5
  "description": "",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "keywords": [],
9
9
  "dependencies": {
10
- "@opentelemetry/api": "1.8.0",
11
- "@opentelemetry/context-async-hooks": "^1.22",
12
- "@opentelemetry/instrumentation": "^0.49 || ^0.50 || ^0.51",
13
- "@opentelemetry/resources": "1.22.0",
10
+ "@opentelemetry/api": "^1.8",
11
+ "@opentelemetry/instrumentation": "^0.49 || ^0.50 || ^0.51 || ^0.52.0 || ^0.53.0",
14
12
  "@opentelemetry/sdk-trace-base": "^1.22",
13
+ "@opentelemetry/context-async-hooks": "^1.22",
14
+ "@opentelemetry/resources": "^1.22.0",
15
15
  "@opentelemetry/semantic-conventions": "1.22.0",
16
16
  "@prisma/debug": "5.19.1",
17
17
  "@prisma/instrumentation": "5.19.1",