@prisma/extension-optimize 0.0.0-dev.202408231713 → 0.0.0-dev.202408231728
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.ts +8 -3
- package/dist/index.js +2 -2
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,11 @@ type OptimizeOptions = {
|
|
|
13
13
|
* create one.
|
|
14
14
|
*/
|
|
15
15
|
token: string;
|
|
16
|
+
/**
|
|
17
|
+
* Same as `sendInterval`
|
|
18
|
+
* @deprecated use `sendInterval` instead
|
|
19
|
+
*/
|
|
20
|
+
minSendInterval?: number;
|
|
16
21
|
/**
|
|
17
22
|
* The minimum interval (in milliseconds) for sending batched Prisma
|
|
18
23
|
* operations to the Prisma Optimize interface.
|
|
@@ -20,13 +25,13 @@ type OptimizeOptions = {
|
|
|
20
25
|
* @default 500
|
|
21
26
|
* @remarks setting this value too low may impact your app performance.
|
|
22
27
|
*/
|
|
23
|
-
|
|
28
|
+
sendInterval?: number;
|
|
24
29
|
/**
|
|
25
30
|
* The maximum time a query can be waited for before being discarded. If a
|
|
26
31
|
* query takes too long to complete, it will be discarded. Increase this if
|
|
27
32
|
* you have very slow queries.
|
|
28
33
|
*
|
|
29
|
-
* @default
|
|
34
|
+
* @default 10000
|
|
30
35
|
* @remarks when below `minSendInterval`, it defaults to `minSendInterval`.
|
|
31
36
|
*/
|
|
32
37
|
sendTimeout?: number;
|
|
@@ -43,6 +48,6 @@ type OptimizeOptions = {
|
|
|
43
48
|
*/
|
|
44
49
|
showToast?: boolean;
|
|
45
50
|
};
|
|
46
|
-
declare function withOptimize({ enable, ingestionUrl, dashboardUrl,
|
|
51
|
+
declare function withOptimize({ enable, ingestionUrl, dashboardUrl, sendInterval, sendTimeout, showToast, token, }: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
|
|
47
52
|
|
|
48
53
|
export { type OptimizeOptions, PROD_DASHBOARD_URL, PROD_INGESTION_URL, withOptimize };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`:
|
|
1
|
+
"use strict";var re=Object.create;var S=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty;var pe=(n,e)=>{for(var t in e)S(n,t,{get:e[t],enumerable:!0})},v=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ie(e))!ae.call(n,r)&&r!==t&&S(n,r,{get:()=>e[r],enumerable:!(s=se(e,r))||s.enumerable});return n};var g=(n,e,t)=>(t=n!=null?re(oe(n)):{},v(e||!n||!n.__esModule?S(t,"default",{value:n,enumerable:!0}):t,n)),ce=n=>v(S({},"__esModule",{value:!0}),n);var Ie={};pe(Ie,{PROD_DASHBOARD_URL:()=>Z,PROD_INGESTION_URL:()=>Y,withOptimize:()=>ye});module.exports=ce(Ie);var W=require("@opentelemetry/api"),X=require("@prisma/client/extension");function me(n,e){let t;return async function(s,r,a){let o=new URL(s,n),p=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});t&&p.set("prisma-optimize-jwt",t);let c=await fetch(o,{method:r,headers:p,body:JSON.stringify(a)});if(!c.ok){let f=await c.text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${c.status} ${c.statusText}: ${f}`)}let d=c.headers.get("prisma-optimize-jwt");return d&&(t=d),c}}function R(n,e){let t=me(n,e);return{request:t,post:(s,r)=>t(s,"POST",r)}}var u=g(require("fs")),P=g(require("path")),E=require("stream"),A=require("stream/promises"),q=g(require("kleur")),O=require("node-notifier"),j=g(require("xdg-app-paths")),le="https://avatars.githubusercontent.com/u/17219288?s=96",{bold:de,underline:ue}=q.default;async function z(n){let e=new j.default("prisma-optimize").config();u.default.mkdirSync(e,{recursive:!0});let t=P.default.resolve(e,"avatar.png");if(!u.default.existsSync(t)){let c=await fetch(le);if(c.ok&&c.body!=null){let d=u.default.createWriteStream(t,{flags:"wx"});await(0,A.finished)(E.Readable.fromWeb(c.body).pipe(d))}}let s="See your Optimize dashboard at:",r=s.length,a=`${ue(de(n))}`,o=n.length,p=Math.max(r,o)+2;console.log("\u250C"+"\u2500".repeat(p)+"\u2510"),console.log("\u2502 "+s+" ".repeat(p-r-2)+" \u2502"),console.log("\u2502 "+a+" ".repeat(p-o-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(p)+"\u2518"),(0,O.notify)({timeout:10,open:n,subtitle:"Your dashboard is ready! \u{1F680} ",message:"Click to open",title:"Prisma Optimize",icon:u.default.existsSync(t)?t:void 0,contentImage:u.default.existsSync(t)?t:void 0})}var M=require("@opentelemetry/api"),H=require("@opentelemetry/context-async-hooks"),L=require("@opentelemetry/instrumentation"),$=require("@opentelemetry/resources"),U=require("@opentelemetry/sdk-trace-base"),I=require("@opentelemetry/semantic-conventions"),D=require("@prisma/instrumentation");var i=require("zod");async function _(n,e){e.length>0&&await n.post("/ingest",e)}async function k(n,e){return await(await n.post("/schema",{schema:e})).text()}function m(n){return n[0]*1e3+n[1]/1e6}var l=require("zod"),b=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=he(()=>void this.forceFlush(),this.sendInterval)}onStart(e){let{parentSpanId:t,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],this.waitSpans[r]=this.spans[r]),t!==void 0&&(this.spans[t]?this.spans[t].children.push(this.spans[r]):(this.spans[t]={spanId:t,kind:"future",children:[this.spans[r]],retries:0},this.waitSpans[t]=this.spans[t]))}cleanSpan(e){if(e===void 0)return;let t=e.spanId;for(let s of e.children)this.cleanSpan(s);delete this.spans[t],delete this.rootSpans[t],delete this.waitSpans[t],this.onClean(e)}async forceFlush(){await this.pendingSend;let e=Object.values(this.rootSpans).flatMap(t=>{let{data:s}=this.treeShape.safeParse(t);return s?[{original:t,pruned:s}]:[]});e.length>0&&(this.pendingSend=this.onFlush(e).finally(()=>{e.forEach(({original:t})=>this.cleanSpan(t))}));for(let t of Object.values(this.waitSpans))++t.retries*this.sendInterval>this.sendTimeout&&this.cleanSpan(t)}async shutdown(){await this.forceFlush(),this.spans={},this.rootSpans={},this.waitSpans={}}onEnd(){}};function he(n,e){let t=!1;return()=>{t===!1&&(t=!0,setTimeout(()=>(t=!1)||n(),e))}}var h={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 fe=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine:db_query"),...h})}),x=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine"),...h}),children:i.z.array(fe).nonempty()}),F=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:connect"),...h})}),Se=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:operation"),...h}),children:i.z.union([i.z.tuple([x]),i.z.tuple([F,x]),i.z.tuple([x,F])])}),y=class extends b{requests={};errors={};schemaHash;apiClient;constructor(e){super({treeShape:Se,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=k(this.apiClient,e.schema)}setRequest(e){this.requests[e.spanId]=e}setError(e){this.errors[e.spanId]=e}onClean(e){let t=e.spanId;delete this.requests[t],delete this.errors[t]}async onFlush(e){let t=await this.schemaHash,s=[];for(let{pruned:r}of e){let{value:a}=r,o=a.spanContext().spanId;this.requests[o]&&s.push({hash:t,sql:ge(r),ts:m(a.startTime),connect:be(r),error:this.errors[o]?.error??null,model:this.requests[o].model??null,operation:this.requests[o].operation,args:this.requests[o]?.args??{},latency:m(a.endTime)-m(a.startTime)})}await _(this.apiClient,s)}};function ge(n){return n.children.find(({value:r})=>r.name==="prisma:engine").children.filter(({value:r})=>r.name==="prisma:engine:db_query").sort((r,a)=>m(r.value.startTime)-m(a.value.startTime)).reduce((r,a)=>{let o=a.value.attributes["db.statement"];return typeof o=="string"?`${r}${o}
|
|
2
|
+
`:r},"")}function be(n){let{value:e}=n.children.find(({value:t})=>t.name==="prisma:client:connect")??{};return e?m(e.endTime)-m(e.startTime):!1}function N(n){let e=new H.AsyncHooksContextManager().enable();M.context.setGlobalContextManager(e);let t=new U.BasicTracerProvider({resource:new $.Resource({[I.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[I.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),s=new y(n);return t.addSpanProcessor(s),(0,L.registerInstrumentations)({tracerProvider:t,instrumentations:[new D.PrismaInstrumentation]}),t.register(),s}function J(n){return n._previewFeatures?.includes("tracing")}function Q(n){return n._engineConfig.inlineSchema}function V(n){if(n instanceof Error)return n.stack??n.message;switch(typeof n){case"undefined":return"undefined";case"object":{let e;return n!==null&&typeof n.toString=="function"&&(e=n.toString()),typeof e=="string"&&e!=="[object Object]"?e:JSON.stringify(n)}default:return String(n)}}var B=require("@prisma/client/extension"),G=B.Prisma.defineExtension(n=>n.$extends({}));var Y="https://optimize-ingestion.datacdn.workers.dev/",Z="https://optimize.prisma.io";function ye({enable:n=!0,ingestionUrl:e=Y,dashboardUrl:t=Z,sendInterval:s=500,sendTimeout:r=1e4,showToast:a=!0,token:o}){return n?(a&&z(t).then().catch(p=>{console.error("Failed to show toast",p)}),X.Prisma.defineExtension(p=>{let c=Q(p),d=R(e,o),f=N({schema:c,apiClient:d,sendInterval:s,sendTimeout:r});if(!J(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return p.$extends({query:{async $allOperations({query:K,model:ee,operation:te,args:C}){let T=W.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");f.setRequest({spanId:T,model:ee,operation:te,args:C});try{return await K(C)}catch(w){let ne=V(w);throw f.setError({spanId:T,error:ne}),w}}}})})):G}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.
|
|
3
|
+
"version": "0.0.0-dev.202408231728",
|
|
4
4
|
"sideEffects": false,
|
|
5
5
|
"description": "",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"hono": "4.4.6",
|
|
30
30
|
"tsup": "8.0.2",
|
|
31
31
|
"vitest": "1.4.0",
|
|
32
|
-
"common": "0.0.0-dev.
|
|
32
|
+
"common": "0.0.0-dev.202408231728"
|
|
33
33
|
},
|
|
34
34
|
"peerDependencies": {
|
|
35
35
|
"@prisma/client": "5.x"
|