Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@kikko-land/kikko

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kikko-land/kikko - npm Package Compare versions

Comparing version 0.13.0 to 0.14.0

6

CHANGELOG.md
# @kikko-land/core
## 0.14.0
### Minor Changes
- 0ac4b28: Use console.info for queries logs
## 0.13.0

@@ -4,0 +10,0 @@

174

dist/index.es.js

@@ -7,18 +7,18 @@ import { deepEqual as z } from "fast-equals";

throw new Error("Not in transaction.");
const a = e.__state.localState.transactionState.current, i = [], r = (o) => (m, p) => {
const a = e.__state.localState.transactionState.current, r = [], i = (o) => (m, p) => {
if (a.id === p.id) {
t(o, m, a);
for (const c of i)
for (const c of r)
c();
}
};
i.push(
r.push(
e.__state.sharedState.eventsEmitter.on(
"transactionCommitted",
r("committed")
i("committed")
)
), i.push(
), r.push(
e.__state.sharedState.eventsEmitter.on(
"transactionRollbacked",
r("rollbacked")
i("rollbacked")
)

@@ -31,10 +31,10 @@ );

async emit(t, ...a) {
const i = e[t] || [];
for (const r of i)
await r(...a);
const r = e[t] || [];
for (const i of r)
await i(...a);
},
on(t, a) {
return (e[t] = e[t] || []).push(a), () => {
const i = e[t] || [];
e[t] = i.filter((r) => r !== a);
const r = e[t] || [];
e[t] = r.filter((i) => i !== a);
};

@@ -60,9 +60,9 @@ }

},
set value(i) {
set value(r) {
if (this.isStopped)
throw new Error(`reactiveVar ${t.label} is stopped!`);
if (!(a && z(this.__state.value, i))) {
this.__state.value = i;
for (const r of this.__state.subscriptions)
r(i);
if (!(a && z(this.__state.value, r))) {
this.__state.value = r;
for (const i of this.__state.subscriptions)
i(r);
}

@@ -75,3 +75,3 @@ },

},
subscribe(i, r = !0) {
subscribe(r, i = !0) {
if (this.isStopped)

@@ -81,9 +81,9 @@ throw new Error(`reactiveVar ${t.label} is stopped!`);

const m = (p) => {
o && o(), o = i(p);
o && o(), o = r(p);
};
return this.__state.subscriptions.push(m), r && m(this.__state.value), () => {
return this.__state.subscriptions.push(m), i && m(this.__state.value), () => {
this.__state.subscriptions = this.__state.subscriptions.filter((p) => p !== m);
};
},
waitTill(i, r) {
waitTill(r, i) {
const o = new N(

@@ -109,3 +109,3 @@ `waitUntil for reactiveVar ${t.label} is stopped due to stop signal`

if (u.push(
((f = r == null ? void 0 : r.stopIf) == null ? void 0 : f.subscribe((l) => {
((f = i == null ? void 0 : i.stopIf) == null ? void 0 : f.subscribe((l) => {
!l || (n(), T(o));

@@ -116,5 +116,5 @@ }, !0)) || (() => {

this.subscribe((l) => {
!i(l) || (n(), s());
!r(l) || (n(), s());
}, !0)
), (r == null ? void 0 : r.timeout) === void 0 || typeof (r == null ? void 0 : r.timeout) == "number") {
), (i == null ? void 0 : i.timeout) === void 0 || typeof (i == null ? void 0 : i.timeout) == "number") {
const l = setTimeout(

@@ -124,3 +124,3 @@ () => {

},
(r == null ? void 0 : r.timeout) === void 0 ? 12e4 : r.timeout
(i == null ? void 0 : i.timeout) === void 0 ? 12e4 : i.timeout
);

@@ -143,4 +143,4 @@ u.push(() => {

this.__state.subscriptions = [];
for (const i of this.__state.onStop)
i();
for (const r of this.__state.onStop)
r();
this.__state.onStop = [], this.__state.isStopped = !0;

@@ -152,7 +152,7 @@ }

__state: {
sharedState: { runningState: a, dbName: i }
sharedState: { runningState: a, dbName: r }
}
} = e;
if (a.value !== "running")
throw new Error(`Failed to start ${t()}, db ${i} is stopping`);
throw new Error(`Failed to start ${t()}, db ${r} is stopping`);
};

@@ -162,3 +162,3 @@ function C() {

const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", a = t.length;
for (let i = 0; i < 32; i++)
for (let r = 0; r < 32; r++)
e += t.charAt(Math.floor(Math.random() * a));

@@ -174,11 +174,11 @@ return e;

const {
localState: { transactionState: i },
sharedState: { dbBackend: r, logFns: o },
localState: { transactionState: r },
sharedState: { dbBackend: i, logFns: o },
sharedState: m
} = e.__state;
if (i.current || M(e, () => JSON.stringify(t)), a && ((d = i.current) == null ? void 0 : d.id) !== a.transactionId)
if (r.current || M(e, () => JSON.stringify(t)), a && ((d = r.current) == null ? void 0 : d.id) !== a.transactionId)
throw new Error(
`Cannot run queries in a transaction that is not the current one. Transaction opts: ${JSON.stringify(
a
)}, local transaction: ${JSON.stringify(i)}`
)}, local transaction: ${JSON.stringify(r)}`
);

@@ -190,4 +190,4 @@ const p = k(), {

} = await (async () => {
const h = a || (i.current ? {
transactionId: i.current.id,
const h = a || (r.current ? {
transactionId: r.current.id,
containsTransactionStart: !1,

@@ -207,3 +207,3 @@ containsTransactionFinish: !1,

return {
...await r.execPreparedQuery(
...await i.execPreparedQuery(
_.preparedQuery,

@@ -218,3 +218,3 @@ t.preparedValues,

return {
...await r.execQueries(_, h),
...await i.execQueries(_, h),
textQueries: _.map((w) => w.text)

@@ -255,3 +255,3 @@ };

`))(), U = `%c[${e.__state.sharedState.dbName}] ` + [
(f = i.current) != null && f.id ? `[tr_id=${(l = i.current) == null ? void 0 : l.id.substring(0, 6)}]` : "",
(f = r.current) != null && f.id ? `[tr_id=${(l = r.current) == null ? void 0 : l.id.substring(0, 6)}]` : "",
w,

@@ -262,6 +262,6 @@ (s == null ? void 0 : s.sendTime) !== void 0 ? `sendTime=${(s.sendTime / 1e3).toFixed(4)}` : "",

`totalTime=${((u - p) / 1e3).toFixed(4)}`
].filter((S) => S.length !== 0).join(" "), P = (R = m.transactionsStates.byId[(F = (y = i.current) == null ? void 0 : y.id) != null ? F : ""]) == null ? void 0 : R.i;
].filter((S) => S.length !== 0).join(" "), P = (R = m.transactionsStates.byId[(F = (y = r.current) == null ? void 0 : y.id) != null ? F : ""]) == null ? void 0 : R.i;
o.logQuery(U, P);
}
const n = (q = m.transactionsStates.byId[(A = (I = i.current) == null ? void 0 : I.id) != null ? A : ""]) == null ? void 0 : q.performance;
const n = (q = m.transactionsStates.byId[(A = (I = r.current) == null ? void 0 : I.id) != null ? A : ""]) == null ? void 0 : q.performance;
return n && (c.some((h) => h.performance.execTime !== void 0) && (n.execTime === void 0 && (n.execTime = 0), n.execTime += c.reduce(

@@ -281,12 +281,12 @@ (h, _) => {

}, b = async (e, t, a) => {
const i = [
const r = [
...e.__state.localState.queriesMiddlewares,
K
].reverse();
let r = (o) => Promise.resolve(o);
for (const o of i) {
const m = r;
r = (p) => o({ ...p, next: m });
let i = (o) => Promise.resolve(o);
for (const o of r) {
const m = i;
i = (p) => o({ ...p, next: m });
}
return await r({
return await i({
db: e,

@@ -305,6 +305,6 @@ result: [],

const B = (e, t, a) => {
const i = e.__state.sharedState.logFns;
const r = e.__state.sharedState.logFns;
if (e.__state.localState.suppressLog)
return;
const r = [
const i = [
a.prepareTime === void 0 ? "" : `prepareTime=${(a.prepareTime / 1e3).toFixed(4)}`,

@@ -317,12 +317,12 @@ a.execTime === void 0 ? "" : `execTime=${(a.execTime / 1e3).toFixed(4)}`,

].filter((o) => o.length !== 0).join(" ");
i.logTrFinish(
r.logTrFinish(
`%c[${e.__state.sharedState.dbName}][tr_id=${t.slice(
0,
6
)}] Transaction finished with ${r}`
)}] Transaction finished with ${i}`
);
}, X = async (e, t, a) => {
const {
localState: { transactionState: i },
sharedState: { eventsEmitter: r, transactionsStates: o, dbBackend: m, logFns: p }
localState: { transactionState: r },
sharedState: { eventsEmitter: i, transactionsStates: o, dbBackend: m, logFns: p }
} = e.__state;

@@ -333,3 +333,3 @@ if (m.isUsualTransactionDisabled)

);
if (i.current)
if (r.current)
return await a(e);

@@ -366,3 +366,3 @@ M(e, () => "transaction");

try {
await r.emit("transactionWillStart", e, c), await b(
await i.emit("transactionWillStart", e, c), await b(
e,

@@ -385,6 +385,6 @@ {

}
), await r.emit("transactionStarted", e, c);
), await i.emit("transactionStarted", e, c);
try {
const u = await a(e);
return await r.emit("transactionWillCommit", e, c), await b(
return await i.emit("transactionWillCommit", e, c), await b(
e,

@@ -400,5 +400,5 @@ { type: "usual", values: [g`COMMIT`] },

}
), await r.emit("transactionCommitted", e, c), u;
), await i.emit("transactionCommitted", e, c), u;
} catch (u) {
p.logError("Rollback transaction", u), await r.emit("transactionWillRollback", e, c);
p.logError("Rollback transaction", u), await i.emit("transactionWillRollback", e, c);
try {

@@ -420,3 +420,3 @@ await b(

}
throw await r.emit("transactionRollbacked", e, c), u;
throw await i.emit("transactionRollbacked", e, c), u;
}

@@ -443,6 +443,6 @@ } finally {

const {
localState: { transactionState: i },
sharedState: { eventsEmitter: r, transactionsStates: o, dbBackend: m, logFns: p }
localState: { transactionState: r },
sharedState: { eventsEmitter: i, transactionsStates: o, dbBackend: m, logFns: p }
} = e.__state;
if (i.current)
if (r.current)
throw new Error(

@@ -495,3 +495,3 @@ "You are running atomic transaction inside of a transaction. Consider moving atomic transaction call to runAfterTransaction callback."

try {
await r.emit("transactionWillStart", e, u), await r.emit("transactionStarted", e, u), await b(
await i.emit("transactionWillStart", e, u), await i.emit("transactionStarted", e, u), await b(
e,

@@ -507,3 +507,3 @@ { type: "usual", values: f },

}
), await r.emit("transactionWillCommit", e, u), await r.emit("transactionCommitted", e, u);
), await i.emit("transactionWillCommit", e, u), await i.emit("transactionCommitted", e, u);
try {

@@ -516,3 +516,3 @@ for (const l of s)

} catch (l) {
p.logError("Rollback transaction", l), await r.emit("transactionWillRollback", e, u), await r.emit("transactionRollbacked", e, u);
p.logError("Rollback transaction", l), await i.emit("transactionWillRollback", e, u), await i.emit("transactionRollbacked", e, u);
try {

@@ -528,8 +528,8 @@ for (const y of T)

}
}, L = ["yellow", "cyan", "magenta"], ie = async ({
}, L = ["yellow", "cyan", "magenta"], re = async ({
dbName: e,
plugins: t,
queriesMiddlewares: a,
dbBackend: i,
suppressLog: r,
dbBackend: r,
suppressLog: i,
logFns: o

@@ -540,3 +540,3 @@ }) => {

const f = typeof d == "number" ? L[d % L.length] : void 0;
console.log(
console.info(
...f ? [

@@ -552,3 +552,3 @@ n,

logTrFinish: (n) => {
console.log(
console.info(
n,

@@ -561,3 +561,3 @@ "color: #fff; background-color: #1da1f2; padding: 2px 4px; border-radius: 2px"

{ label: "runningState" }
), c = (await i)({
), c = (await r)({
dbName: e

@@ -578,3 +578,3 @@ }), s = {

transactionState: {},
suppressLog: Boolean(r)
suppressLog: Boolean(i)
}

@@ -655,5 +655,5 @@ },

), O = (e) => ({ id: e }), ee = async (e, t) => {
const { current: a, queue: i } = e.value;
if (a || i.length > 0) {
const r = e.waitTill(
const { current: a, queue: r } = e.value;
if (a || r.length > 0) {
const i = e.waitTill(
(o) => {

@@ -668,7 +668,7 @@ var m;

e.value = {
queue: [...i, t],
queue: [...r, t],
current: a
};
try {
await r;
await i;
} catch (o) {

@@ -690,3 +690,3 @@ throw e.value = {

}, te = (e, t) => {
const { current: a, queue: i } = e.value;
const { current: a, queue: r } = e.value;
if ((a == null ? void 0 : a.id) !== t.id)

@@ -698,3 +698,3 @@ throw new Error(

);
e.value = { queue: i.slice(1), current: i[0] };
e.value = { queue: r.slice(1), current: r[0] };
}, le = async (e) => {

@@ -714,11 +714,11 @@ try {

if (t) {
const i = O(t.transactionId);
t.containsTransactionStart ? await ee(e, i) : await e.waitTill((r) => {
const r = O(t.transactionId);
t.containsTransactionStart ? await ee(e, r) : await e.waitTill((i) => {
var o;
return ((o = r.current) == null ? void 0 : o.id) === i.id;
}), a = i;
return ((o = i.current) == null ? void 0 : o.id) === r.id;
}), a = r;
} else
await e.waitTill((i) => {
var r;
return ((r = i.current) == null ? void 0 : r.id) === void 0;
await e.waitTill((r) => {
var i;
return ((i = r.current) == null ? void 0 : i.id) === void 0;
});

@@ -736,3 +736,3 @@ return a;

k as getTime,
ie as initDbClient,
re as initDbClient,
ce as initJobsState,

@@ -739,0 +739,0 @@ C as makeId,

(function(m,C){typeof exports=="object"&&typeof module<"u"?C(exports,require("fast-equals"),require("@kikko-land/boono-sql")):typeof define=="function"&&define.amd?define(["exports","fast-equals","@kikko-land/boono-sql"],C):(m=typeof globalThis<"u"?globalThis:m||self,C(m.core={},m.fastEquals,m.boonoSql))})(this,function(m,C,g){"use strict";const q=(e,t)=>{if(!e.__state.localState.transactionState.current)throw new Error("Not in transaction.");const a=e.__state.localState.transactionState.current,r=[],i=o=>(f,T)=>{if(a.id===T.id){t(o,f,a);for(const c of r)c()}};r.push(e.__state.sharedState.eventsEmitter.on("transactionCommitted",i("committed"))),r.push(e.__state.sharedState.eventsEmitter.on("transactionRollbacked",i("rollbacked")))};function Y(){const e={};return{async emit(t,...a){const r=e[t]||[];for(const i of r)await i(...a)},on(t,a){return(e[t]=e[t]||[]).push(a),()=>{const r=e[t]||[];e[t]=r.filter(i=>i!==a)}}}}class k extends Error{}class x extends Error{}const R=(e,t)=>{const a=t.deduplicate===void 0?!0:t.deduplicate;return{__state:{subscriptions:[],value:e,isStopped:!1,onStop:[]},get isStopped(){return this.__state.isStopped},set value(r){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);if(!(a&&C.deepEqual(this.__state.value,r))){this.__state.value=r;for(const i of this.__state.subscriptions)i(r)}},get value(){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);return this.__state.value},subscribe(r,i=!0){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);let o;const f=T=>{o&&o(),o=r(T)};return this.__state.subscriptions.push(f),i&&f(this.__state.value),()=>{this.__state.subscriptions=this.__state.subscriptions.filter(T=>T!==f)}},waitTill(r,i){const o=new x(`waitUntil for reactiveVar ${t.label} is stopped due to stop signal`),f=new k(`waitUntil for reactiveVar ${t.label} is timed out`),T=new x(`waitUntil for reactiveVar ${t.label} is stopped due to reactive var stop`);if(this.isStopped)throw new Error(`reactiveVar ${t.label} is stopped!`);return new Promise((s,h)=>{var p;let u=[];const n=()=>{queueMicrotask(()=>{for(const l of u)l();u=[]})};if(u.push(((p=i==null?void 0:i.stopIf)==null?void 0:p.subscribe(l=>{!l||(n(),h(o))},!0))||(()=>{})),u.push(this.subscribe(l=>{!r(l)||(n(),s())},!0)),(i==null?void 0:i.timeout)===void 0||typeof(i==null?void 0:i.timeout)=="number"){const l=setTimeout(()=>{n(),h(f)},(i==null?void 0:i.timeout)===void 0?12e4:i.timeout);u.push(()=>{clearTimeout(l)})}const d=()=>{n(),h(T)};this.__state.onStop.push(d),u.push(()=>{this.__state.onStop=this.__state.onStop.filter(l=>l!==d)})})},stop(){if(this.isStopped)throw new Error(`reactiveVar ${t.label} is already stopped!`);this.__state.subscriptions=[];for(const r of this.__state.onStop)r();this.__state.onStop=[],this.__state.isStopped=!0}}},y=typeof performance<"u"?()=>performance.now():()=>Date.now(),J=(e,t)=>{const{__state:{sharedState:{runningState:a,dbName:r}}}=e;if(a.value!=="running")throw new Error(`Failed to start ${t()}, db ${r} is stopping`)};function I(){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=t.length;for(let r=0;r<32;r++)e+=t.charAt(Math.floor(Math.random()*a));return e}const H=e=>e.filter(t=>t!==null),K=e=>e.reduce((t,a)=>t+a,0),Q=e=>K(H(e)),X=async({db:e,queries:t,transactionOpts:a})=>{var d,p,l,$,B,U,P,z,G;const{localState:{transactionState:r},sharedState:{dbBackend:i,logFns:o},sharedState:f}=e.__state;if(r.current||J(e,()=>JSON.stringify(t)),a&&((d=r.current)==null?void 0:d.id)!==a.transactionId)throw new Error(`Cannot run queries in a transaction that is not the current one. Transaction opts: ${JSON.stringify(a)}, local transaction: ${JSON.stringify(r)}`);const T=y(),{result:c,performance:s,textQueries:h}=await(async()=>{const _=a||(r.current?{transactionId:r.current.id,containsTransactionStart:!1,containsTransactionFinish:!1,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}:void 0);if(t.type==="prepared"){const w=t.query.toSql();if(w._values.length!==0)throw new Error("You can't use prepared var through ${} for runPreparedQuery. Please, manually specify variables with '?'.");const v=w.preparedQuery.text;return{...await i.execPreparedQuery(w.preparedQuery,t.preparedValues,_),textQueries:[v]}}else{const w=t.values.map(v=>v.preparedQuery);return{...await i.execQueries(w,_),textQueries:w.map(v=>v.text)}}})(),u=y();if(!e.__state.localState.suppressLog){const _=(S,F)=>`${S}=${(F/1e3).toFixed(4)}`,w=(()=>{if(t.type==="prepared"){const S=c[0],F=[S.performance.prepareTime!==void 0?_("prepareTime",Q(c.map(b=>b.performance.prepareTime))):"",S.performance.execTime!==void 0?_("execTime",Q(c.map(b=>b.performance.execTime))):""].filter(b=>b.length!==0).join(" ");return[[h[0].slice(0,1e3),`for ${t.preparedValues.length} values`,F].filter(b=>b.length!==0).join(" ")]}else return c.map(({performance:S},F)=>{const b=[S.prepareTime!==void 0?_("prepareTime",S.prepareTime):"",S.execTime!==void 0?_("execTime",S.execTime):""].filter(A=>A.length!==0).join(" ");return[h[F].slice(0,1e3),b].filter(A=>A.length!==0).join(" ")})})(),v=(()=>w.length===1?w[0]:`
`+w.map(S=>`{${S}}`).join(`
`))(),le=`%c[${e.__state.sharedState.dbName}] `+[(p=r.current)!=null&&p.id?`[tr_id=${(l=r.current)==null?void 0:l.id.substring(0,6)}]`:"",v,(s==null?void 0:s.sendTime)!==void 0?`sendTime=${(s.sendTime/1e3).toFixed(4)}`:"",(s==null?void 0:s.receiveTime)!==void 0?`receiveTime=${(s.receiveTime/1e3).toFixed(4)}`:"",(s==null?void 0:s.blockTime)!==void 0?`blockTime=${(s.blockTime/1e3).toFixed(4)}`:"",`totalTime=${((u-T)/1e3).toFixed(4)}`].filter(S=>S.length!==0).join(" "),ue=(U=f.transactionsStates.byId[(B=($=r.current)==null?void 0:$.id)!=null?B:""])==null?void 0:U.i;o.logQuery(le,ue)}const n=(G=f.transactionsStates.byId[(z=(P=r.current)==null?void 0:P.id)!=null?z:""])==null?void 0:G.performance;return n&&(c.some(_=>_.performance.execTime!==void 0)&&(n.execTime===void 0&&(n.execTime=0),n.execTime+=c.reduce((_,w)=>{var v;return _+((v=w.performance.execTime)!=null?v:0)},0)),c.some(_=>_.performance.prepareTime!==void 0)&&(n.prepareTime===void 0&&(n.prepareTime=0),n.prepareTime+=c.reduce((_,w)=>{var v;return _+((v=w.performance.prepareTime)!=null?v:0)},0)),s.sendTime&&(n.sendTime||(n.sendTime=0),n.sendTime+=s.sendTime),s.receiveTime&&(n.receiveTime||(n.receiveTime=0),n.receiveTime+=s.receiveTime),s.blockTime&&(n.blockTime||(n.blockTime=0),n.blockTime+=s.blockTime)),{db:e,result:c,performance:s,queries:t}},E=async(e,t,a)=>{const r=[...e.__state.localState.queriesMiddlewares,X].reverse();let i=o=>Promise.resolve(o);for(const o of r){const f=i;i=T=>o({...T,next:f})}return await i({db:e,result:[],performance:{sendTime:void 0,receiveTime:void 0,totalTime:0},queries:t,transactionOpts:a})};let N=0;const L=(e,t,a)=>{const r=e.__state.sharedState.logFns;if(e.__state.localState.suppressLog)return;const i=[a.prepareTime===void 0?"":`prepareTime=${(a.prepareTime/1e3).toFixed(4)}`,a.execTime===void 0?"":`execTime=${(a.execTime/1e3).toFixed(4)}`,a.sendTime===void 0?"":`sendTime=${(a.sendTime/1e3).toFixed(4)}`,a.receiveTime===void 0?"":`receiveTime=${(a.receiveTime/1e3).toFixed(4)}`,a.blockTime===void 0?"":`blockTime=${(a.blockTime/1e3).toFixed(4)}`,`totalTime=${(a.totalTime/1e3).toFixed(4)}`].filter(o=>o.length!==0).join(" ");r.logTrFinish(`%c[${e.__state.sharedState.dbName}][tr_id=${t.slice(0,6)}] Transaction finished with ${i}`)},Z=async(e,t,a)=>{const{localState:{transactionState:r},sharedState:{eventsEmitter:i,transactionsStates:o,dbBackend:f,logFns:T}}=e.__state;if(f.isUsualTransactionDisabled)throw new Error("Usual transactions are disabled for this type of backend. Please, use atomic transactions instead.");if(r.current)return await a(e);J(e,()=>"transaction");const c={id:I(),type:"async"};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:c}}}};const s=y(),h={i:N++,current:c,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};o.byId[c.id]=h;try{await i.emit("transactionWillStart",e,c),await E(e,{type:"usual",values:[g.sql`BEGIN ${g.sql.raw(t.toLocaleUpperCase())} TRANSACTION`]},{transactionId:c.id,containsTransactionStart:!0,containsTransactionFinish:!1,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionStarted",e,c);try{const u=await a(e);return await i.emit("transactionWillCommit",e,c),await E(e,{type:"usual",values:[g.sql`COMMIT`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionCommitted",e,c),u}catch(u){T.logError("Rollback transaction",u),await i.emit("transactionWillRollback",e,c);try{await E(e,{type:"usual",values:[g.sql`ROLLBACK`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!1,containsTransactionRollback:!0,rollbackOnFail:!1,isAtomic:!1})}catch(n){T.logError("Rollback transaction failed",n)}throw await i.emit("transactionRollbacked",e,c),u}}finally{h.performance.totalTime=y()-s,L(e,c.id,h.performance),delete o.byId[c.id]}},j=()=>({__state:{queries:[],afterCommits:[],afterRollbacks:[]},addQuery(e){this.__state.queries.push(e)},afterCommit(e){this.__state.afterCommits.push(e)},afterRollback(e){this.__state.afterRollbacks.push(e)}}),O=async(e,t,a)=>{const{localState:{transactionState:r},sharedState:{eventsEmitter:i,transactionsStates:o,dbBackend:f,logFns:T}}=e.__state;if(r.current)throw new Error("You are running atomic transaction inside of a transaction. Consider moving atomic transaction call to runAfterTransaction callback.");const{inputQueries:c,afterCommits:s,afterRollbacks:h}=await(async()=>{if(Array.isArray(a))return{inputQueries:a,afterCommits:[],afterRollbacks:[]};{const l=j();return await a(l),{inputQueries:l.__state.queries,afterCommits:l.__state.afterCommits,afterRollbacks:l.__state.afterRollbacks}}})(),u={id:I(),type:"atomic"},n={i:N++,current:u,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:u}}}},o.byId[u.id]=n;const d=y(),p=[];f.isAtomicRollbackCommitDisabled||p.push(g.sql`BEGIN ${g.sql.raw(t.toUpperCase())} TRANSACTION`),p.push(...c.map(l=>l.toSql())),f.isAtomicRollbackCommitDisabled||p.push(g.sql`COMMIT`);try{await i.emit("transactionWillStart",e,u),await i.emit("transactionStarted",e,u),await E(e,{type:"usual",values:p},{transactionId:u.id,containsTransactionStart:!0,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!0,isAtomic:!0}),await i.emit("transactionWillCommit",e,u),await i.emit("transactionCommitted",e,u);try{for(const l of s)l()}catch(l){T.logError("Error in afterCommit callback",l)}}catch(l){T.logError("Rollback transaction",l),await i.emit("transactionWillRollback",e,u),await i.emit("transactionRollbacked",e,u);try{for(const $ of h)$()}catch($){T.logError("Error in afterRallback callback",$)}throw l}finally{n.performance.totalTime=y()-d,L(e,u.id,n.performance),delete o.byId[u.id]}},D=["yellow","cyan","magenta"],ee=async({dbName:e,plugins:t,queriesMiddlewares:a,dbBackend:r,suppressLog:i,logFns:o})=>{const f=o||{logQuery:(n,d)=>{const p=typeof d=="number"?D[d%D.length]:void 0;console.log(...p?[n,`color: ${p}; background-color: #202124; padding: 2px 4px; border-radius: 2px`]:[n,"padding: 0"])},logError:(n,d)=>{console.error(n,d)},logTrFinish:n=>{console.log(n,"color: #fff; background-color: #1da1f2; padding: 2px 4px; border-radius: 2px")}},T=R("running",{label:"runningState"}),c=(await r)({dbName:e}),s={__state:{sharedState:{clientId:I(),dbBackend:c,dbName:e,runningState:T,eventsEmitter:Y(),transactionsStates:{byId:{}},logFns:f},localState:{queriesMiddlewares:a||[],transactionState:{},suppressLog:Boolean(i)}},runInTransaction(n,d){return Z(this,(d==null?void 0:d.type)||"deferred",n)},async runInAtomicTransaction(n,d){return await O(this,(d==null?void 0:d.type)||"deferred",n)},async runQueries(n){return(await E(this,{type:"usual",values:n.map(p=>p.toSql())})).result.map(({rows:p})=>p)},async runQuery(n){return(await this.runQueries([n]))[0]},async runPreparedQuery(n,d){return(await E(this,{type:"prepared",query:n,preparedValues:d})).result.map(({rows:l})=>l)},runAfterTransactionCommitted(n){return q(this,(d,p,l)=>{d==="committed"&&n(p,l)})},runAfterTransactionRollbacked(n){q(s,(d,p,l)=>{d==="rollbacked"&&n(p,l)})}};let h=s;const u=()=>s.__state.sharedState.runningState.value;if(u()!=="running"||(await c.initialize(),u()!=="running"))return s;for(const n of t||[])h=n(h);return await s.__state.sharedState.eventsEmitter.emit("initialized",s),h},te=async e=>{e.__state.sharedState.runningState.value="stopping",await e.__state.sharedState.dbBackend.stop(),e.__state.sharedState.runningState.value="stopped",queueMicrotask(()=>{e.__state.sharedState.runningState.stop()})},ae=(e,t)=>t({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}}),ie=e=>({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}}),M=e=>{const{current:t,queue:a}=e;return`Current running transaction job: ${JSON.stringify(t,null,2)}, queue of transaction jobs: ${JSON.stringify(a,null,2)}`},re=()=>R({queue:[],current:void 0},{label:"jobsState"}),ne=e=>({id:e}),V=async(e,t)=>{const{current:a,queue:r}=e.value;if(a||r.length>0){const i=e.waitTill(o=>{var f;return((f=o.current)==null?void 0:f.id)===t.id},{timeout:12e4});e.value={queue:[...r,t],current:a};try{await i}catch(o){throw e.value={...e.value,queue:e.value.queue.filter(f=>f.id!==t.id)},o instanceof k?new k(`Timeout error while trnsaction job acquire: '${o.message}'. Is it a dead lock? ${M(e.value)}, jobToAcquire: ${JSON.stringify(t,null,2)}`):o}}else e.value={queue:[],current:t}},W=(e,t)=>{const{current:a,queue:r}=e.value;if((a==null?void 0:a.id)!==t.id)throw new Error(`Can't release job that is not currently running, ${M(e.value)}, toRelease: ${JSON.stringify(t,null,2)}`);e.value={queue:r.slice(1),current:r[0]}},se=async e=>{try{return e.waitTill(({queue:t,current:a})=>t.length===0&&a===void 0,{timeout:12e4})}catch(t){throw t instanceof k?new k(`Timeout error while awaiting all jobs done: '${t.message}'. Is it a dead lock?`):t}},oe=async(e,t)=>{let a;if(t){const r=ne(t.transactionId);t.containsTransactionStart?await V(e,r):await e.waitTill(i=>{var o;return((o=i.current)==null?void 0:o.id)===r.id}),a=r}else await e.waitTill(r=>{var i;return((i=r.current)==null?void 0:i.id)===void 0});return a},ce=(e,t,a)=>{if(t&&(!a||(a==null?void 0:a.containsTransactionFinish)||(a==null?void 0:a.containsTransactionRollback))&&W(e,t),!t&&a)throw new Error("Transaction job was not started, nothing to release!")};m.StoppedError=x,m.TimeoutError=k,m.acquireJob=V,m.acquireWithTrJobOrWait=oe,m.getTime=y,m.initDbClient=ee,m.initJobsState=re,m.makeId=I,m.reactiveVar=R,m.releaseJob=W,m.releaseTrJobIfPossible=ce,m.stopDb=te,m.suppressLog=ae,m.whenAllJobsDone=se,m.withSuppressedLog=ie;for(const e in g)e!=="default"&&!m.hasOwnProperty(e)&&Object.defineProperty(m,e,{enumerable:!0,get:()=>g[e]});Object.defineProperties(m,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
`))(),le=`%c[${e.__state.sharedState.dbName}] `+[(p=r.current)!=null&&p.id?`[tr_id=${(l=r.current)==null?void 0:l.id.substring(0,6)}]`:"",v,(s==null?void 0:s.sendTime)!==void 0?`sendTime=${(s.sendTime/1e3).toFixed(4)}`:"",(s==null?void 0:s.receiveTime)!==void 0?`receiveTime=${(s.receiveTime/1e3).toFixed(4)}`:"",(s==null?void 0:s.blockTime)!==void 0?`blockTime=${(s.blockTime/1e3).toFixed(4)}`:"",`totalTime=${((u-T)/1e3).toFixed(4)}`].filter(S=>S.length!==0).join(" "),ue=(U=f.transactionsStates.byId[(B=($=r.current)==null?void 0:$.id)!=null?B:""])==null?void 0:U.i;o.logQuery(le,ue)}const n=(G=f.transactionsStates.byId[(z=(P=r.current)==null?void 0:P.id)!=null?z:""])==null?void 0:G.performance;return n&&(c.some(_=>_.performance.execTime!==void 0)&&(n.execTime===void 0&&(n.execTime=0),n.execTime+=c.reduce((_,w)=>{var v;return _+((v=w.performance.execTime)!=null?v:0)},0)),c.some(_=>_.performance.prepareTime!==void 0)&&(n.prepareTime===void 0&&(n.prepareTime=0),n.prepareTime+=c.reduce((_,w)=>{var v;return _+((v=w.performance.prepareTime)!=null?v:0)},0)),s.sendTime&&(n.sendTime||(n.sendTime=0),n.sendTime+=s.sendTime),s.receiveTime&&(n.receiveTime||(n.receiveTime=0),n.receiveTime+=s.receiveTime),s.blockTime&&(n.blockTime||(n.blockTime=0),n.blockTime+=s.blockTime)),{db:e,result:c,performance:s,queries:t}},E=async(e,t,a)=>{const r=[...e.__state.localState.queriesMiddlewares,X].reverse();let i=o=>Promise.resolve(o);for(const o of r){const f=i;i=T=>o({...T,next:f})}return await i({db:e,result:[],performance:{sendTime:void 0,receiveTime:void 0,totalTime:0},queries:t,transactionOpts:a})};let N=0;const L=(e,t,a)=>{const r=e.__state.sharedState.logFns;if(e.__state.localState.suppressLog)return;const i=[a.prepareTime===void 0?"":`prepareTime=${(a.prepareTime/1e3).toFixed(4)}`,a.execTime===void 0?"":`execTime=${(a.execTime/1e3).toFixed(4)}`,a.sendTime===void 0?"":`sendTime=${(a.sendTime/1e3).toFixed(4)}`,a.receiveTime===void 0?"":`receiveTime=${(a.receiveTime/1e3).toFixed(4)}`,a.blockTime===void 0?"":`blockTime=${(a.blockTime/1e3).toFixed(4)}`,`totalTime=${(a.totalTime/1e3).toFixed(4)}`].filter(o=>o.length!==0).join(" ");r.logTrFinish(`%c[${e.__state.sharedState.dbName}][tr_id=${t.slice(0,6)}] Transaction finished with ${i}`)},Z=async(e,t,a)=>{const{localState:{transactionState:r},sharedState:{eventsEmitter:i,transactionsStates:o,dbBackend:f,logFns:T}}=e.__state;if(f.isUsualTransactionDisabled)throw new Error("Usual transactions are disabled for this type of backend. Please, use atomic transactions instead.");if(r.current)return await a(e);J(e,()=>"transaction");const c={id:I(),type:"async"};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:c}}}};const s=y(),h={i:N++,current:c,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};o.byId[c.id]=h;try{await i.emit("transactionWillStart",e,c),await E(e,{type:"usual",values:[g.sql`BEGIN ${g.sql.raw(t.toLocaleUpperCase())} TRANSACTION`]},{transactionId:c.id,containsTransactionStart:!0,containsTransactionFinish:!1,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionStarted",e,c);try{const u=await a(e);return await i.emit("transactionWillCommit",e,c),await E(e,{type:"usual",values:[g.sql`COMMIT`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!1,isAtomic:!1}),await i.emit("transactionCommitted",e,c),u}catch(u){T.logError("Rollback transaction",u),await i.emit("transactionWillRollback",e,c);try{await E(e,{type:"usual",values:[g.sql`ROLLBACK`]},{transactionId:c.id,containsTransactionStart:!1,containsTransactionFinish:!1,containsTransactionRollback:!0,rollbackOnFail:!1,isAtomic:!1})}catch(n){T.logError("Rollback transaction failed",n)}throw await i.emit("transactionRollbacked",e,c),u}}finally{h.performance.totalTime=y()-s,L(e,c.id,h.performance),delete o.byId[c.id]}},j=()=>({__state:{queries:[],afterCommits:[],afterRollbacks:[]},addQuery(e){this.__state.queries.push(e)},afterCommit(e){this.__state.afterCommits.push(e)},afterRollback(e){this.__state.afterRollbacks.push(e)}}),O=async(e,t,a)=>{const{localState:{transactionState:r},sharedState:{eventsEmitter:i,transactionsStates:o,dbBackend:f,logFns:T}}=e.__state;if(r.current)throw new Error("You are running atomic transaction inside of a transaction. Consider moving atomic transaction call to runAfterTransaction callback.");const{inputQueries:c,afterCommits:s,afterRollbacks:h}=await(async()=>{if(Array.isArray(a))return{inputQueries:a,afterCommits:[],afterRollbacks:[]};{const l=j();return await a(l),{inputQueries:l.__state.queries,afterCommits:l.__state.afterCommits,afterRollbacks:l.__state.afterRollbacks}}})(),u={id:I(),type:"atomic"},n={i:N++,current:u,performance:{prepareTime:0,execTime:0,freeTime:0,sendTime:0,receiveTime:0,totalTime:0,blockTime:0}};e={...e,__state:{...e.__state,localState:{...e.__state.localState,transactionState:{current:u}}}},o.byId[u.id]=n;const d=y(),p=[];f.isAtomicRollbackCommitDisabled||p.push(g.sql`BEGIN ${g.sql.raw(t.toUpperCase())} TRANSACTION`),p.push(...c.map(l=>l.toSql())),f.isAtomicRollbackCommitDisabled||p.push(g.sql`COMMIT`);try{await i.emit("transactionWillStart",e,u),await i.emit("transactionStarted",e,u),await E(e,{type:"usual",values:p},{transactionId:u.id,containsTransactionStart:!0,containsTransactionFinish:!0,containsTransactionRollback:!1,rollbackOnFail:!0,isAtomic:!0}),await i.emit("transactionWillCommit",e,u),await i.emit("transactionCommitted",e,u);try{for(const l of s)l()}catch(l){T.logError("Error in afterCommit callback",l)}}catch(l){T.logError("Rollback transaction",l),await i.emit("transactionWillRollback",e,u),await i.emit("transactionRollbacked",e,u);try{for(const $ of h)$()}catch($){T.logError("Error in afterRallback callback",$)}throw l}finally{n.performance.totalTime=y()-d,L(e,u.id,n.performance),delete o.byId[u.id]}},D=["yellow","cyan","magenta"],ee=async({dbName:e,plugins:t,queriesMiddlewares:a,dbBackend:r,suppressLog:i,logFns:o})=>{const f=o||{logQuery:(n,d)=>{const p=typeof d=="number"?D[d%D.length]:void 0;console.info(...p?[n,`color: ${p}; background-color: #202124; padding: 2px 4px; border-radius: 2px`]:[n,"padding: 0"])},logError:(n,d)=>{console.error(n,d)},logTrFinish:n=>{console.info(n,"color: #fff; background-color: #1da1f2; padding: 2px 4px; border-radius: 2px")}},T=R("running",{label:"runningState"}),c=(await r)({dbName:e}),s={__state:{sharedState:{clientId:I(),dbBackend:c,dbName:e,runningState:T,eventsEmitter:Y(),transactionsStates:{byId:{}},logFns:f},localState:{queriesMiddlewares:a||[],transactionState:{},suppressLog:Boolean(i)}},runInTransaction(n,d){return Z(this,(d==null?void 0:d.type)||"deferred",n)},async runInAtomicTransaction(n,d){return await O(this,(d==null?void 0:d.type)||"deferred",n)},async runQueries(n){return(await E(this,{type:"usual",values:n.map(p=>p.toSql())})).result.map(({rows:p})=>p)},async runQuery(n){return(await this.runQueries([n]))[0]},async runPreparedQuery(n,d){return(await E(this,{type:"prepared",query:n,preparedValues:d})).result.map(({rows:l})=>l)},runAfterTransactionCommitted(n){return q(this,(d,p,l)=>{d==="committed"&&n(p,l)})},runAfterTransactionRollbacked(n){q(s,(d,p,l)=>{d==="rollbacked"&&n(p,l)})}};let h=s;const u=()=>s.__state.sharedState.runningState.value;if(u()!=="running"||(await c.initialize(),u()!=="running"))return s;for(const n of t||[])h=n(h);return await s.__state.sharedState.eventsEmitter.emit("initialized",s),h},te=async e=>{e.__state.sharedState.runningState.value="stopping",await e.__state.sharedState.dbBackend.stop(),e.__state.sharedState.runningState.value="stopped",queueMicrotask(()=>{e.__state.sharedState.runningState.stop()})},ae=(e,t)=>t({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}}),ie=e=>({...e,__state:{...e.__state,localState:{...e.__state.localState,suppressLog:!0}}}),M=e=>{const{current:t,queue:a}=e;return`Current running transaction job: ${JSON.stringify(t,null,2)}, queue of transaction jobs: ${JSON.stringify(a,null,2)}`},re=()=>R({queue:[],current:void 0},{label:"jobsState"}),ne=e=>({id:e}),V=async(e,t)=>{const{current:a,queue:r}=e.value;if(a||r.length>0){const i=e.waitTill(o=>{var f;return((f=o.current)==null?void 0:f.id)===t.id},{timeout:12e4});e.value={queue:[...r,t],current:a};try{await i}catch(o){throw e.value={...e.value,queue:e.value.queue.filter(f=>f.id!==t.id)},o instanceof k?new k(`Timeout error while trnsaction job acquire: '${o.message}'. Is it a dead lock? ${M(e.value)}, jobToAcquire: ${JSON.stringify(t,null,2)}`):o}}else e.value={queue:[],current:t}},W=(e,t)=>{const{current:a,queue:r}=e.value;if((a==null?void 0:a.id)!==t.id)throw new Error(`Can't release job that is not currently running, ${M(e.value)}, toRelease: ${JSON.stringify(t,null,2)}`);e.value={queue:r.slice(1),current:r[0]}},se=async e=>{try{return e.waitTill(({queue:t,current:a})=>t.length===0&&a===void 0,{timeout:12e4})}catch(t){throw t instanceof k?new k(`Timeout error while awaiting all jobs done: '${t.message}'. Is it a dead lock?`):t}},oe=async(e,t)=>{let a;if(t){const r=ne(t.transactionId);t.containsTransactionStart?await V(e,r):await e.waitTill(i=>{var o;return((o=i.current)==null?void 0:o.id)===r.id}),a=r}else await e.waitTill(r=>{var i;return((i=r.current)==null?void 0:i.id)===void 0});return a},ce=(e,t,a)=>{if(t&&(!a||(a==null?void 0:a.containsTransactionFinish)||(a==null?void 0:a.containsTransactionRollback))&&W(e,t),!t&&a)throw new Error("Transaction job was not started, nothing to release!")};m.StoppedError=x,m.TimeoutError=k,m.acquireJob=V,m.acquireWithTrJobOrWait=oe,m.getTime=y,m.initDbClient=ee,m.initJobsState=re,m.makeId=I,m.reactiveVar=R,m.releaseJob=W,m.releaseTrJobIfPossible=ce,m.stopDb=te,m.suppressLog=ae,m.whenAllJobsDone=se,m.withSuppressedLog=ie;for(const e in g)e!=="default"&&!m.hasOwnProperty(e)&&Object.defineProperty(m,e,{enumerable:!0,get:()=>g[e]});Object.defineProperties(m,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
//# sourceMappingURL=index.umd.js.map
{
"name": "@kikko-land/kikko",
"version": "0.13.0",
"version": "0.14.0",
"author": "Sergey Popov",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -45,3 +45,3 @@ import { IPrimitiveValue, ISql, ISqlAdapter } from "@kikko-land/boono-sql";

console.log(
console.info(
...(color

@@ -59,3 +59,3 @@ ? [

logTrFinish: (msg: string) => {
console.log(
console.info(
msg,

@@ -62,0 +62,0 @@ `color: #fff; background-color: #1da1f2; padding: 2px 4px; border-radius: 2px`

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc