@event-driven-io/emmett-postgresql 0.20.1 → 0.20.2-alpha.3

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.js CHANGED
@@ -1,9 +1,9 @@
1
- import{dumbo as ft}from"@event-driven-io/dumbo";import"commander";var z=(e=>(e.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",e.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",e.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",e))(z||{}),H=e=>typeof e=="number"&&e===e,Y=e=>typeof e=="string";var U=e=>typeof e=="function"&&e.prototype&&e.prototype.constructor===e,J=class K extends Error{errorCode;constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:H(t)?t:500,a=t&&typeof t=="object"&&"message"in t?t.message:Y(t)?t:`Error with status code '${n}' ocurred during Emmett processing`;super(a),this.errorCode=n,Object.setPrototypeOf(this,K.prototype)}},Z=class ee extends J{constructor(t,n,a){super({errorCode:412,message:a??`Expected version ${n.toString()} does not match current ${t?.toString()}`}),this.current=t,this.expected=n,Object.setPrototypeOf(this,ee.prototype)}};import{v4 as $t}from"uuid";import{ReadableStream as Ce,TransformStream as be,WritableStream as Me}from"web-streams-polyfill";import{v4 as Vt}from"uuid";import{v4 as Ue}from"uuid";import Qe from"async-retry";var $=(e,t,n)=>({type:e,data:t,metadata:n});var xe="__emt:GlobalStreamCaughtUp";var te=e=>$(xe,e,{globalPosition:e.globalPosition});var j="STREAM_EXISTS",Q="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK",we=(e,t,n)=>t===O?!0:t==Q?e===n:t==j?e!==n:e===t,ne=(e,t,n)=>{if(t??=O,!we(e,t,n))throw new B(e,t)},B=class ae extends Z{constructor(t,n){super(t?.toString(),n?.toString()),Object.setPrototypeOf(this,ae.prototype)}};var Fe={ReadableStream:Ce,WritableStream:Me,TransformStream:be},Qt=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,x;if(globalThis&&globalThis.WritableStream&&globalThis.ReadableStream&&globalThis.TransformStream)x=globalThis;else try{x=await import("node:stream/web")}catch{x=Fe}var g=x;var Bt=class extends g.TransformStream{_currentPosition;_logPosition;constructor(e){super({start:t=>{let n=0n;for(let a of e)t.enqueue(a),n=a.metadata.globalPosition;t.enqueue(te({globalPosition:n}))},transform:(t,n)=>{this._currentPosition=t.metadata.globalPosition,n.enqueue(t),!(this._currentPosition<this._logPosition)&&n.enqueue(te({globalPosition:this._currentPosition}))}}),this._currentPosition=this._logPosition=e.length>0?e[e.length-1].metadata.globalPosition:0n}set logPosition(e){this._logPosition=e}},$e=(e,t={})=>new oe(e,t),oe=class extends g.TransformStream{constructor(e,t={}){super({cancel:n=>{console.log("Stream was canceled. Reason:",n),this.stopChecking()}}),this.onNoActiveReaderCallback=e,this.streamId=t?.streamId??Ue(),this.onNoActiveReaderCallback=e,this.startChecking(t?.intervalCheckInMs??20)}checkInterval=null;streamId;_isStopped=!1;get hasActiveSubscribers(){return!this._isStopped}startChecking(e){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},e)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}};var u=(e,t)=>{if(je(e))return e.equals(t);if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((o,i)=>u(o,t[i]));if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e===t;if(Array.isArray(t))return!1;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length||!n.every(o=>a.includes(o)))return!1;for(let o in e)if(!(e[o]instanceof Function&&t[o]instanceof Function)&&!u(e[o],t[o]))return!1;return!0},je=e=>e&&typeof e=="object"&&"equals"in e&&typeof e.equals=="function";var Be=async(e,t)=>t===void 0||t.retries===0?e():Qe(async n=>{try{return await e()}catch(a){throw t?.shouldRetryError&&!t.shouldRetryError(a)&&n(a),a}},t??{retries:0});var re=e=>e;var Xe=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},P={stringify:(e,t)=>JSON.stringify(t?.map?t.map(e):e,(n,a)=>typeof a=="bigint"?a.toString():a),parse:(e,t)=>{let n=JSON.parse(e,t?.reviver);if(t?.typeCheck&&!t?.typeCheck(n))throw new Xe(e);return t?.map?t.map(n):n}};var Ve=e=>new g.TransformStream({transform(t,n){e(t)&&n.enqueue(t)}}),Ge=e=>new g.TransformStream({transform(t,n){n.enqueue(e(t))}}),ke=(e,t)=>new ie(e,t),ie=class extends g.TransformStream{accumulator;reducer;constructor(e,t){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=t,this.reducer=e}},We=(e,t,n={forever:!0,minTimeout:25})=>new g.TransformStream({start(a){Be(()=>qe(e,t,a),n).catch(o=>{a.error(o)})}}),qe=async(e,t,n)=>{let a=e().getReader();try{let o;do{let i=await a.read();o=i.done,await t(i,n),o&&n.terminate()}while(!o)}finally{a.releaseLock()}},ze=e=>new se(e),se=class extends g.TransformStream{count=0;skip;constructor(e){super({transform:(t,n)=>{this.count++,this.count>this.skip&&n.enqueue(t)}}),this.skip=e}},He=e=>new g.TransformStream({transform(t,n){n.enqueue(t),e(t)&&n.terminate()}}),Ye=e=>new g.TransformStream({async transform(t,n){if(!e(t)){n.enqueue(t);return}await Promise.resolve(),n.terminate()}}),Je=e=>new ce(e),ce=class extends g.TransformStream{count=0;limit;constructor(e){super({transform:(t,n)=>{this.count<this.limit?(this.count++,n.enqueue(t)):n.terminate()}}),this.limit=e}},Ke=e=>new g.TransformStream({start(t){let n=setTimeout(()=>{t.terminate()},e),a=t.terminate.bind(t);t.terminate=()=>{clearTimeout(n),a()}},transform(t,n){n.enqueue(t)}}),Ze={filter:Ve,take:Je,TakeTransformStream:ce,skip:ze,SkipTransformStream:se,map:Ge,notifyAboutNoActiveReadersStream:$e,NotifyAboutNoActiveReadersStream:oe,reduce:ke,ReduceTransformStream:ie,retry:We,stopAfter:He,stopOn:Ye,waitAtMost:Ke},{retry:Wt}=Ze;var h=class extends Error{constructor(e){super(e)}};var me=e=>{throw new h(e??"That should not ever happened, right?")};var le=(e,t,n)=>{if(!u(e,t))throw new h(n??`subObj:
2
- ${P.stringify(t)}
1
+ import{dumbo as ht}from"@event-driven-io/dumbo";var k=t=>typeof t=="number"&&t===t,W=t=>typeof t=="string";var M=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,H=class q extends Error{errorCode;constructor(e){let n=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:k(e)?e:500,o=e&&typeof e=="object"&&"message"in e?e.message:W(e)?e:`Error with status code '${n}' ocurred during Emmett processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,q.prototype)}},z=class Y extends H{constructor(e,n,o){super({errorCode:412,message:o??`Expected version ${n.toString()} does not match current ${e?.toString()}`}),this.current=e,this.expected=n,Object.setPrototypeOf(this,Y.prototype)}};import{v4 as jt}from"uuid";import{TransformStream as Bt}from"web-streams-polyfill";import{v4 as Vt}from"uuid";import{v4 as Ae}from"uuid";import{TransformStream as Le}from"web-streams-polyfill";import we from"async-retry";import{ReadableStream as qt}from"web-streams-polyfill";import"web-streams-polyfill";import{TransformStream as Me}from"web-streams-polyfill";import{TransformStream as Ue}from"web-streams-polyfill";import{TransformStream as je}from"web-streams-polyfill";import{TransformStream as Be}from"web-streams-polyfill";import{TransformStream as Ge}from"web-streams-polyfill";import{TransformStream as We}from"web-streams-polyfill";import{TransformStream as qe}from"web-streams-polyfill";import{TransformStream as Ye}from"web-streams-polyfill";import{TransformStream as Ke}from"web-streams-polyfill";var J=(t,e,n)=>({type:t,data:e,metadata:n});var F="STREAM_EXISTS",U="STREAM_DOES_NOT_EXIST",N="NO_CONCURRENCY_CHECK",Re=(t,e,n)=>e===N?!0:e==U?t===n:e==F?t!==n:t===e,K=(t,e,n)=>{if(e??=N,!Re(t,e,n))throw new $(t,e)},$=class Z extends z{constructor(e,n){super(e?.toString(),n?.toString()),Object.setPrototypeOf(this,Z.prototype)}};var De=(t,e={})=>new ee(t,e),ee=class extends Le{constructor(t,e={}){super({cancel:n=>{console.log("Stream was canceled. Reason:",n),this.stopChecking()}}),this.onNoActiveReaderCallback=t,this.streamId=e?.streamId??Ae(),this.onNoActiveReaderCallback=t,this.startChecking(e?.intervalCheckInMs??20)}checkInterval=null;streamId;_isStopped=!1;get hasActiveSubscribers(){return!this._isStopped}startChecking(t){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},t)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}};var T=(t,e)=>{if(xe(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((a,r)=>T(a,e[r]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length||!n.every(a=>o.includes(a)))return!1;for(let a in t){if(t[a]instanceof Function&&e[a]instanceof Function)continue;if(!T(t[a],e[a]))return!1}return!0},xe=t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var Ce=async(t,e)=>e===void 0||e.retries===0?t():we(async n=>{try{return await t()}catch(o){throw e?.shouldRetryError&&!e.shouldRetryError(o)&&n(o),o}},e??{retries:0});var te=t=>t;var be=class extends Error{constructor(t){super(`Cannot parse! ${t}`)}},h={stringify:(t,e)=>JSON.stringify(e?.map?e.map(t):t,(n,o)=>typeof o=="bigint"?o.toString():o),parse:(t,e)=>{let n=JSON.parse(t,e?.reviver);if(e?.typeCheck&&!e?.typeCheck(n))throw new be(t);return e?.map?e.map(n):n}};var Fe=t=>new Me({transform(e,n){t(e)&&n.enqueue(e)}}),$e=t=>new Ue({transform(e,n){n.enqueue(t(e))}}),Qe=(t,e)=>new ne(t,e),ne=class extends je{accumulator;reducer;constructor(t,e){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=e,this.reducer=t}},Xe=(t,e,n={forever:!0,minTimeout:25})=>new Be({start(o){Ce(()=>Ve(t,e,o),n).catch(a=>{o.error(a)})}}),Ve=async(t,e,n)=>{let a=t().getReader();try{let r;do{let l=await a.read();r=l.done,await e(l,n),r&&n.terminate()}while(!r)}finally{a.releaseLock()}},ke=t=>new oe(t),oe=class extends Ge{count=0;skip;constructor(t){super({transform:(e,n)=>{this.count++,this.count>this.skip&&n.enqueue(e)}}),this.skip=t}},He=t=>new We({transform(e,n){n.enqueue(e),t(e)&&n.terminate()}}),ze=t=>new qe({async transform(e,n){if(!t(e)){n.enqueue(e);return}await Promise.resolve(),n.terminate()}}),Je=t=>new ae(t),ae=class extends Ye{count=0;limit;constructor(t){super({transform:(e,n)=>{this.count<this.limit?(this.count++,n.enqueue(e)):n.terminate()}}),this.limit=t}},Ze=t=>new Ke({start(e){let n=setTimeout(()=>{e.terminate()},t),o=e.terminate.bind(e);e.terminate=()=>{clearTimeout(n),o()}},transform(e,n){n.enqueue(e)}}),et={filter:Fe,take:Je,TakeTransformStream:ae,skip:ke,SkipTransformStream:oe,map:$e,notifyAboutNoActiveReadersStream:De,NotifyAboutNoActiveReadersStream:ee,reduce:Qe,ReduceTransformStream:ne,retry:Xe,stopAfter:He,stopOn:ze,waitAtMost:Ze},{retry:rn}=et;var y=class extends Error{constructor(t){super(t)}};var re=t=>{throw new y(t??"That should not ever happened, right?")};var ie=(t,e,n)=>{if(!T(t,e))throw new y(n??`subObj:
2
+ ${h.stringify(e)}
3
3
  is not equal to
4
- ${P.stringify(e)}`)};function T(e,t){if(!e)throw new h(t??"Condition is false")}function et(e,t){if(!e)throw new h(t??"Condition is not truthy")}function y(e,t,n){if(e!==t)throw new h(`${n??"Objects are not equal"}:
5
- Expected: ${P.stringify(e)}
6
- Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects are equal: ${P.stringify(e)}`)}function X(e){de(e,null),et(e)}var A=e=>({isEmpty:()=>y(e.length,0),isNotEmpty:()=>de(e.length,0),hasSize:t=>y(e.length,t),containsElements:(...t)=>{T(t.every(n=>t.some(a=>u(n,a))))},containsExactlyInAnyOrder:(...t)=>{y(e.length,t.length),T(e.every(n=>t.some(a=>u(n,a))))},containsExactlyInAnyOrderElementsOf:t=>{y(e.length,t.length),T(e.every(n=>t.some(a=>u(n,a))))},containsExactlyElementsOf:t=>{y(e.length,t.length);for(let n=0;n<e.length;n++)T(u(e[n],t[n]))},containsExactly:t=>{y(e.length,1),T(u(e[0],t))},contains:t=>{T(e.some(n=>u(n,t)))},containsOnlyOnceElementsOf:t=>{T(t.map(n=>e.filter(a=>u(a,n)).length).filter(n=>n===1).length===t.length)},containsAnyOf:(...t)=>{T(e.some(n=>t.some(a=>u(n,a))))},allMatch:t=>{T(e.every(t))},anyMatches:t=>{T(e.some(t))},allMatchAsync:async t=>{for(let n of e)T(await t(n))}});import"pg";import"@event-driven-io/dumbo";import"@event-driven-io/dumbo";import{pongoClient as tt}from"@event-driven-io/pongo";var L=(e,t)=>{let{pool:n,connectionString:a,inDatabase:o,inCollection:i}=t;return n.withConnection(async p=>{let m=tt(a,{connectionOptions:{connection:p}});try{let E=m.db(o).collection(i);return e(E)}finally{await m.close()}})},Ee=e=>{let{_id:t,_version:n,...a}=e;return a},nt=(e,t)=>("_id"in t&&y(t._id,e._id,`Document ids are not matching! Expected: ${t._id}, actual: ${e._id}`),le(Ee(e),Ee(t))),at=(e,t)=>n=>L(async a=>{let o=await a.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);X(o),nt(o,e)},{...t,...n}),ot=(e,t)=>n=>L(async a=>{let o=await a.find("withId"in t?{_id:t.withId}:t.matchingFilter);y(e.length,o.length,"Different Documents Count than expected");for(let i=0;i<e.length;i++)A(o).contains(e[i])},{...t,...n}),rt=(e,t)=>n=>L(async a=>{let o=await a.find("withId"in t?{_id:t.withId}:t.matchingFilter);y(e,o.length,"Different Documents Count than expected")},{...t,...n}),pe=e=>t=>L(async n=>{let a=await n.find("withId"in e?{_id:e.withId}:e.matchingFilter);A(a).isNotEmpty()},{...e,...t}),ve=e=>t=>L(async n=>{let a=await n.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);X(a)},{...e,...t}),rn={fromCollection:e=>({withId:t=>({toBeEqual:n=>at(n,{withId:t,inCollection:e}),toExist:()=>pe({withId:t,inCollection:e}),notToExist:()=>ve({withId:t,inCollection:e})}),matching:t=>({toBeTheSame:n=>ot(n,{matchingFilter:t,inCollection:e}),toHaveCount:n=>rt(n,{matchingFilter:t,inCollection:e}),toExist:()=>pe({matchingFilter:t,inCollection:e}),notToExist:()=>ve({matchingFilter:t,inCollection:e})})})};import{pongoClient as it}from"@event-driven-io/pongo";var st=({handle:e,canHandle:t})=>V({canHandle:t,handle:async(n,a)=>{let{connectionString:o,client:i}=a,p=it(o,{connectionOptions:{client:i}});await e(n,{...a,pongo:p})}}),ct=e=>{let{collectionName:t,getDocumentId:n,canHandle:a}=e;return st({handle:async(o,{pongo:i})=>{let p=i.db().collection(t);for(let m of o)await p.handle(n(m),async E=>"initialState"in e?await e.evolve(E??e.initialState(),m):await e.evolve(E,m))},canHandle:a})},dn=e=>ct({...e,getDocumentId:t=>t.metadata.streamName});import{dumbo as _e}from"@event-driven-io/dumbo";import{v4 as Te}from"uuid";var yn={for:e=>{{let{projection:t,...n}=e,{connectionString:a}=n;return o=>({when:(i,p)=>{let m=[],E=async c=>{let d=0n,l=p?.numberOfTimes??1;for(let v of[...o,...Array.from({length:l}).flatMap(()=>i)])m.push({...v,metadata:{globalPosition:++d,streamPosition:d,streamName:`test-${Te()}`,eventId:Te(),...v.metadata??{}}});await c.withTransaction(v=>w({events:m,projections:[t],connection:{connectionString:a,transaction:v}}))};return{then:async(c,d)=>{let l=_e(n);try{await E(l);let v=await c({pool:l,connectionString:a});v!==void 0&&v===!1&&me(d??"Projection specification didn't match the criteria")}finally{await l.close()}},thenThrows:async(...c)=>{let d=_e(n);try{throw await E(d),new h("Handler did not fail as expected")}catch(l){if(l instanceof h)throw l;if(c.length===0)return;if(!U(c[0])){T(c[0](l),`Error didn't match the error condition: ${l?.toString()}`);return}T(l instanceof c[0],`Caught error is not an instance of the expected type: ${l?.toString()}`),c[1]&&T(c[1](l),`Error didn't match the error condition: ${l?.toString()}`)}finally{await d.close()}}}}})}}},mt=(e,t)=>({...t,metadata:{...t.metadata??{},streamName:t.metadata?.streamName??e}}),lt=(e,t)=>t.map(n=>mt(e,n)),fn=lt,dt=(e,t)=>async({pool:{execute:n}})=>{let a=await n.query(e);A(t).containsExactlyInAnyOrder(...a.rows)},hn={query:e=>({resultRows:{toBeTheSame:t=>dt(e,t)}})};var w=async e=>{let{projections:t,events:n,connection:{transaction:a,connectionString:o}}=e,i=n.map(E=>E.type),p=t.filter(E=>E.canHandle.some(c=>i.includes(c))),m=await a.connection.open();for(let E of p)await E.handle(n,{connectionString:o,client:m,transaction:a,execute:a.execute})},V=e=>re(e),Et=(e,...t)=>V({canHandle:t,handle:async(n,a)=>{let o=await e(n,a);await a.execute.batchCommand(o)}}),On=(e,...t)=>Et(async(n,a)=>{let o=[];for(let i of n)o.push(await e(i,a));return o},...t);import"@event-driven-io/dumbo";import{rawSql as pt,single as vt,sql as D}from"@event-driven-io/dumbo";import{v4 as _t}from"uuid";var C="emt",_="global",R="emt:default",Dn={module:`${C}:module:${_}`,tenant:`${C}:tenant:${_}`},b={partition:{name:"partition"},isArchived:{name:"is_archived"}},s={name:`${C}_streams`,columns:{partition:b.partition,isArchived:b.isArchived}},r={name:`${C}_events`,columns:{partition:b.partition,isArchived:b.isArchived}};var ue=pt(`CREATE OR REPLACE FUNCTION emt_append_event(
4
+ ${h.stringify(t)}`)};function _(t,e){if(!t)throw new y(e??"Condition is false")}function tt(t,e){if(!t)throw new y(e??"Condition is not truthy")}function S(t,e,n){if(t!==e)throw new y(`${n??"Objects are not equal"}:
5
+ Expected: ${h.stringify(t)}
6
+ Actual:${h.stringify(e)}`)}function se(t,e,n){if(t===e)throw new y(n??`Objects are equal: ${h.stringify(t)}`)}function j(t){se(t,null),tt(t)}var R=t=>({isEmpty:()=>S(t.length,0),isNotEmpty:()=>se(t.length,0),hasSize:e=>S(t.length,e),containsElements:(...e)=>{_(e.every(n=>e.some(o=>T(n,o))))},containsExactlyInAnyOrder:(...e)=>{S(t.length,e.length),_(t.every(n=>e.some(o=>T(n,o))))},containsExactlyInAnyOrderElementsOf:e=>{S(t.length,e.length),_(t.every(n=>e.some(o=>T(n,o))))},containsExactlyElementsOf:e=>{S(t.length,e.length);for(let n=0;n<t.length;n++)_(T(t[n],e[n]))},containsExactly:e=>{S(t.length,1),_(T(t[0],e))},contains:e=>{_(t.some(n=>T(n,e)))},containsOnlyOnceElementsOf:e=>{_(e.map(n=>t.filter(o=>T(o,n)).length).filter(n=>n===1).length===e.length)},containsAnyOf:(...e)=>{_(t.some(n=>e.some(o=>T(n,o))))},allMatch:e=>{_(t.every(e))},anyMatches:e=>{_(t.some(e))},allMatchAsync:async e=>{for(let n of t)_(await e(n))}});import"pg";import"@event-driven-io/dumbo";import"@event-driven-io/dumbo";import{pongoClient as nt}from"@event-driven-io/pongo";var A=(t,e)=>{let{pool:n,connectionString:o,inDatabase:a,inCollection:r}=e;return n.withConnection(async l=>{let m=nt(o,{connectionOptions:{connection:l}});try{let p=m.db(a).collection(r);return t(p)}finally{await m.close()}})},ce=t=>{let{_id:e,_version:n,...o}=t;return o},ot=(t,e)=>("_id"in e&&S(e._id,t._id,`Document ids are not matching! Expected: ${e._id}, actual: ${t._id}`),ie(ce(t),ce(e))),at=(t,e)=>n=>A(async o=>{let a=await o.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);j(a),ot(a,t)},{...e,...n}),rt=(t,e)=>n=>A(async o=>{let a=await o.find("withId"in e?{_id:e.withId}:e.matchingFilter);S(t.length,a.length,"Different Documents Count than expected");for(let r=0;r<t.length;r++)R(a).contains(t[r])},{...e,...n}),it=(t,e)=>n=>A(async o=>{let a=await o.find("withId"in e?{_id:e.withId}:e.matchingFilter);S(t,a.length,"Different Documents Count than expected")},{...e,...n}),me=t=>e=>A(async n=>{let o=await n.find("withId"in t?{_id:t.withId}:t.matchingFilter);R(o).isNotEmpty()},{...t,...e}),de=t=>e=>A(async n=>{let o=await n.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);j(o)},{...t,...e}),gn={fromCollection:t=>({withId:e=>({toBeEqual:n=>at(n,{withId:e,inCollection:t}),toExist:()=>me({withId:e,inCollection:t}),notToExist:()=>de({withId:e,inCollection:t})}),matching:e=>({toBeTheSame:n=>rt(n,{matchingFilter:e,inCollection:t}),toHaveCount:n=>it(n,{matchingFilter:e,inCollection:t}),toExist:()=>me({matchingFilter:e,inCollection:t}),notToExist:()=>de({matchingFilter:e,inCollection:t})})})};import{pongoClient as st}from"@event-driven-io/pongo";var ct=({handle:t,canHandle:e})=>Q({canHandle:e,handle:async(n,o)=>{let{connectionString:a,client:r}=o,l=st(a,{connectionOptions:{client:r}});await t(n,{...o,pongo:l})}}),mt=t=>{let{collectionName:e,getDocumentId:n,canHandle:o}=t;return ct({handle:async(a,{pongo:r})=>{let l=r.db().collection(e);for(let m of a)await l.handle(n(m),async p=>"initialState"in t?await t.evolve(p??t.initialState(),m):await t.evolve(p,m))},canHandle:o})},Pn=t=>mt({...t,getDocumentId:e=>e.metadata.streamName});import{dumbo as le}from"@event-driven-io/dumbo";import{v4 as Ee}from"uuid";var wn={for:t=>{{let{projection:e,...n}=t,{connectionString:o}=n;return a=>({when:(r,l)=>{let m=[],p=async c=>{let E=0n,d=l?.numberOfTimes??1;for(let v of[...a,...Array.from({length:d}).flatMap(()=>r)])m.push({...v,metadata:{globalPosition:++E,streamPosition:E,streamName:`test-${Ee()}`,eventId:Ee(),...v.metadata??{}}});await c.withTransaction(v=>D({events:m,projections:[e],connection:{connectionString:o,transaction:v}}))};return{then:async(c,E)=>{let d=le(n);try{await p(d);let v=await c({pool:d,connectionString:o});v!==void 0&&v===!1&&re(E??"Projection specification didn't match the criteria")}finally{await d.close()}},thenThrows:async(...c)=>{let E=le(n);try{throw await p(E),new y("Handler did not fail as expected")}catch(d){if(d instanceof y)throw d;if(c.length===0)return;if(!M(c[0])){_(c[0](d),`Error didn't match the error condition: ${d?.toString()}`);return}_(d instanceof c[0],`Caught error is not an instance of the expected type: ${d?.toString()}`),c[1]&&_(c[1](d),`Error didn't match the error condition: ${d?.toString()}`)}finally{await E.close()}}}}})}}},dt=(t,e)=>({...e,metadata:{...e.metadata??{},streamName:e.metadata?.streamName??t}}),lt=(t,e)=>e.map(n=>dt(t,n)),Cn=lt,Et=(t,e)=>async({pool:{execute:n}})=>{let o=await n.query(t);R(e).containsExactlyInAnyOrder(...o.rows)},bn={query:t=>({resultRows:{toBeTheSame:e=>Et(t,e)}})};var D=async t=>{let{projections:e,events:n,connection:{transaction:o,connectionString:a}}=t,r=n.map(p=>p.type),l=e.filter(p=>p.canHandle.some(c=>r.includes(c))),m=await o.connection.open();for(let p of l)await p.handle(n,{connectionString:a,client:m,transaction:o,execute:o.execute})},Q=t=>te(t),pt=(t,...e)=>Q({canHandle:e,handle:async(n,o)=>{let a=await t(n,o);await o.execute.batchCommand(a)}}),$n=(t,...e)=>pt(async(n,o)=>{let a=[];for(let r of n)a.push(await t(r,o));return a},...e);import"@event-driven-io/dumbo";import{rawSql as vt,single as ut,sql as L}from"@event-driven-io/dumbo";import{v4 as _t}from"uuid";var x="emt",u="global",O="emt:default",Xn={module:`${x}:module:${u}`,tenant:`${x}:tenant:${u}`},w={partition:{name:"partition"},isArchived:{name:"is_archived"}},s={name:`${x}_streams`,columns:{partition:w.partition,isArchived:w.isArchived}},i={name:`${x}_events`,columns:{partition:w.partition,isArchived:w.isArchived}};var pe=vt(`CREATE OR REPLACE FUNCTION emt_append_event(
7
7
  v_event_ids text[],
8
8
  v_events_data jsonb[],
9
9
  v_events_metadata jsonb[],
@@ -51,7 +51,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
51
51
  ) AS event
52
52
  ),
53
53
  all_events_insert AS (
54
- INSERT INTO ${r.name}
54
+ INSERT INTO ${i.name}
55
55
  (stream_id, stream_position, partition, event_data, event_metadata, event_schema_version, event_type, event_id, transaction_id)
56
56
  SELECT
57
57
  v_stream_id, ev.stream_position, v_partition, ev.event_data, ev.event_metadata, ev.schema_version, ev.event_type, ev.event_id, v_transaction_id
@@ -85,7 +85,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
85
85
  RETURN QUERY SELECT TRUE, v_next_stream_position, v_last_global_position, v_transaction_id;
86
86
  END;
87
87
  $$;
88
- `),ge=(e,t,n,a,o)=>e.withTransaction(async i=>{let{execute:p}=i;if(a.length===0)return{success:!1,result:{success:!1}};let m;try{let v=Tt(o?.expectedStreamVersion),I=a.map((N,f)=>({...N,metadata:{streamName:t,eventId:_t(),streamPosition:BigInt(f),...N.metadata}}));m=await gt(p,t,n,I,{expectedStreamVersion:v}),o?.preCommitHook&&await o.preCommitHook(I,{transaction:i})}catch(v){if(!ut(v))throw v;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:E,next_stream_position:c,last_global_position:d,transaction_id:l}=m;return{success:E,result:E&&c&&d&&l?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(d),transactionId:l}:{success:!1}}}),Tt=e=>e===void 0||e===O||e==Q||e==j?null:e,ut=e=>e instanceof Error&&"code"in e&&e.code==="23505",gt=(e,t,n,a,o)=>vt(e.command(D(`SELECT * FROM emt_append_event(
88
+ `),ve=(t,e,n,o,a)=>t.withTransaction(async r=>{let{execute:l}=r;if(o.length===0)return{success:!1,result:{success:!1}};let m;try{let v=Tt(a?.expectedStreamVersion),P=o.map((I,f)=>({...I,metadata:{streamName:e,eventId:_t(),streamPosition:BigInt(f),...I.metadata}}));m=await St(l,e,n,P,{expectedStreamVersion:v}),a?.preCommitHook&&await a.preCommitHook(P,{transaction:r})}catch(v){if(!gt(v))throw v;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:p,next_stream_position:c,last_global_position:E,transaction_id:d}=m;return{success:p,result:p&&c&&E&&d?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(E),transactionId:d}:{success:!1}}}),Tt=t=>t===void 0||t===N||t==U||t==F?null:t,gt=t=>t instanceof Error&&"code"in t&&t.code==="23505",St=(t,e,n,o,a)=>ut(t.command(L(`SELECT * FROM emt_append_event(
89
89
  ARRAY[%s]::text[],
90
90
  ARRAY[%s]::jsonb[],
91
91
  ARRAY[%s]::jsonb[],
@@ -95,22 +95,22 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
95
95
  %L::text,
96
96
  %s::bigint,
97
97
  %L::text
98
- )`,a.map(i=>D("%L",i.metadata.eventId)).join(","),a.map(i=>D("%L",P.stringify(i.data))).join(","),a.map(i=>D("%L",P.stringify(i.metadata??{}))).join(","),a.map(()=>"'1'").join(","),a.map(i=>D("%L",i.type)).join(","),t,n,o?.expectedStreamVersion??"NULL",o?.partition??R)));import{rawSql as S}from"@event-driven-io/dumbo";var Se=S(`CREATE TABLE IF NOT EXISTS ${s.name}(
98
+ )`,o.map(r=>L("%L",r.metadata.eventId)).join(","),o.map(r=>L("%L",h.stringify(r.data))).join(","),o.map(r=>L("%L",h.stringify(r.metadata??{}))).join(","),o.map(()=>"'1'").join(","),o.map(r=>L("%L",r.type)).join(","),e,n,a?.expectedStreamVersion??"NULL",a?.partition??O)));import{rawSql as g}from"@event-driven-io/dumbo";var ue=g(`CREATE TABLE IF NOT EXISTS ${s.name}(
99
99
  stream_id TEXT NOT NULL,
100
100
  stream_position BIGINT NOT NULL,
101
- partition TEXT NOT NULL DEFAULT '${_}__${_}',
101
+ partition TEXT NOT NULL DEFAULT '${u}__${u}',
102
102
  stream_type TEXT NOT NULL,
103
103
  stream_metadata JSONB NOT NULL,
104
104
  is_archived BOOLEAN NOT NULL DEFAULT FALSE,
105
105
  PRIMARY KEY (stream_id, stream_position, partition, is_archived),
106
106
  UNIQUE (stream_id, partition, is_archived)
107
- ) PARTITION BY LIST (partition);`),ye=S(`
107
+ ) PARTITION BY LIST (partition);`),_e=g(`
108
108
  CREATE SEQUENCE IF NOT EXISTS emt_global_event_position;
109
109
 
110
- CREATE TABLE IF NOT EXISTS ${r.name}(
110
+ CREATE TABLE IF NOT EXISTS ${i.name}(
111
111
  stream_id TEXT NOT NULL,
112
112
  stream_position BIGINT NOT NULL,
113
- partition TEXT NOT NULL DEFAULT '${_}',
113
+ partition TEXT NOT NULL DEFAULT '${u}',
114
114
  event_data JSONB NOT NULL,
115
115
  event_metadata JSONB NOT NULL,
116
116
  event_schema_version TEXT NOT NULL,
@@ -121,7 +121,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
121
121
  transaction_id XID8 NOT NULL,
122
122
  created TIMESTAMPTZ NOT NULL DEFAULT now(),
123
123
  PRIMARY KEY (stream_id, stream_position, partition, is_archived)
124
- ) PARTITION BY LIST (partition);`),fe=S(`
124
+ ) PARTITION BY LIST (partition);`),Te=g(`
125
125
  CREATE TABLE IF NOT EXISTS emt_subscriptions(
126
126
  subscription_id TEXT NOT NULL PRIMARY KEY,
127
127
  version INT NOT NULL DEFAULT 1,
@@ -130,11 +130,11 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
130
130
  last_processed_position BIGINT NOT NULL,
131
131
  last_processed_transaction_id BIGINT NOT NULL
132
132
  );
133
- `),he=S(`CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
133
+ `),ge=g(`CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
134
134
  BEGIN
135
135
  RETURN REGEXP_REPLACE(input_name, '[^a-zA-Z0-9_]', '_', 'g');
136
136
  END;
137
- $$ LANGUAGE plpgsql;`),Pe=S(`
137
+ $$ LANGUAGE plpgsql;`),Se=g(`
138
138
  CREATE OR REPLACE FUNCTION emt_add_table_partition(tableName TEXT, partition_name TEXT) RETURNS void AS $$
139
139
  DECLARE
140
140
  v_main_partiton_name TEXT;
@@ -171,74 +171,74 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
171
171
  v_archived_partiton_name, v_main_partiton_name
172
172
  );
173
173
  END;
174
- $$ LANGUAGE plpgsql;`),Ie=S(`
174
+ $$ LANGUAGE plpgsql;`),fe=g(`
175
175
  CREATE OR REPLACE FUNCTION emt_add_partition(partition_name TEXT) RETURNS void AS $$
176
176
  BEGIN
177
- PERFORM emt_add_table_partition('${r.name}', partition_name);
177
+ PERFORM emt_add_table_partition('${i.name}', partition_name);
178
178
  PERFORM emt_add_table_partition('${s.name}', partition_name);
179
179
  END;
180
- $$ LANGUAGE plpgsql;`),Ne=S(`
180
+ $$ LANGUAGE plpgsql;`),ye=g(`
181
181
  CREATE OR REPLACE FUNCTION add_module(new_module TEXT) RETURNS void AS $$
182
182
  BEGIN
183
- -- For ${r.name} table
183
+ -- For ${i.name} table
184
184
  EXECUTE format('
185
185
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
186
186
  FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
187
- emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}'), '${r.name}', new_module, '${_}'
187
+ emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}'), '${i.name}', new_module, '${u}'
188
188
  );
189
189
 
190
190
  EXECUTE format('
191
191
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
192
192
  FOR VALUES IN (FALSE);',
193
- emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}' || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}')
193
+ emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}' || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}')
194
194
  );
195
195
 
196
196
  EXECUTE format('
197
197
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
198
198
  FOR VALUES IN (TRUE);',
199
- emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}' || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || '${_}')
199
+ emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}' || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}')
200
200
  );
201
201
 
202
202
  -- For ${s.name} table
203
203
  EXECUTE format('
204
204
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
205
205
  FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
206
- emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}'), '${s.name}', new_module, '${_}'
206
+ emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}'), '${s.name}', new_module, '${u}'
207
207
  );
208
208
 
209
209
  EXECUTE format('
210
210
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
211
211
  FOR VALUES IN (FALSE);',
212
- emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}' || '_active'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}')
212
+ emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}' || '_active'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}')
213
213
  );
214
214
 
215
215
  EXECUTE format('
216
216
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
217
217
  FOR VALUES IN (TRUE);',
218
- emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}' || '_archived'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${_}')
218
+ emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}' || '_archived'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}')
219
219
  );
220
220
  END;
221
221
  $$ LANGUAGE plpgsql;
222
- `),Oe=S(`
222
+ `),he=g(`
223
223
  CREATE OR REPLACE FUNCTION add_tenant(new_module TEXT, new_tenant TEXT) RETURNS void AS $$
224
224
  BEGIN
225
- -- For ${r.name} table
225
+ -- For ${i.name} table
226
226
  EXECUTE format('
227
227
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
228
228
  FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
229
- emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant), '${r.name}', new_module, new_tenant
229
+ emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant), '${i.name}', new_module, new_tenant
230
230
  );
231
231
 
232
232
  EXECUTE format('
233
233
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
234
234
  FOR VALUES IN (FALSE);',
235
- emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant)
235
+ emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
236
236
  );
237
237
 
238
238
  EXECUTE format('
239
239
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
240
240
  FOR VALUES IN (TRUE);',
241
- emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant)
241
+ emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
242
242
  );
243
243
 
244
244
  -- For ${s.name} table
@@ -261,32 +261,32 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
261
261
  );
262
262
  END;
263
263
  $$ LANGUAGE plpgsql;
264
- `),Re=S(`
264
+ `),Pe=g(`
265
265
  CREATE OR REPLACE FUNCTION add_module_for_all_tenants(new_module TEXT) RETURNS void AS $$
266
266
  DECLARE
267
267
  tenant_record RECORD;
268
268
  BEGIN
269
269
  PERFORM add_module(new_module);
270
270
 
271
- FOR tenant_record IN SELECT DISTINCT tenant FROM ${r.name}
271
+ FOR tenant_record IN SELECT DISTINCT tenant FROM ${i.name}
272
272
  LOOP
273
- -- For ${r.name} table
273
+ -- For ${i.name} table
274
274
  EXECUTE format('
275
275
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
276
276
  FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
277
- emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant), '${r.name}', new_module, tenant_record.tenant
277
+ emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant), '${i.name}', new_module, tenant_record.tenant
278
278
  );
279
279
 
280
280
  EXECUTE format('
281
281
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
282
282
  FOR VALUES IN (FALSE);',
283
- emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant)
283
+ emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
284
284
  );
285
285
 
286
286
  EXECUTE format('
287
287
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
288
288
  FOR VALUES IN (TRUE);',
289
- emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant)
289
+ emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
290
290
  );
291
291
 
292
292
  -- For ${s.name} table
@@ -310,30 +310,30 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
310
310
  END LOOP;
311
311
  END;
312
312
  $$ LANGUAGE plpgsql;
313
- `),Ae=S(`
313
+ `),Ie=g(`
314
314
  CREATE OR REPLACE FUNCTION add_tenant_for_all_modules(new_tenant TEXT) RETURNS void AS $$
315
315
  DECLARE
316
316
  module_record RECORD;
317
317
  BEGIN
318
- FOR module_record IN SELECT DISTINCT partitionname FROM pg_partman.part_config WHERE parent_table = '${r.name}'
318
+ FOR module_record IN SELECT DISTINCT partitionname FROM pg_partman.part_config WHERE parent_table = '${i.name}'
319
319
  LOOP
320
- -- For ${r.name} table
320
+ -- For ${i.name} table
321
321
  EXECUTE format('
322
322
  CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
323
323
  FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
324
- emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant), '${r.name}', module_record.partitionname, new_tenant
324
+ emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant), '${i.name}', module_record.partitionname, new_tenant
325
325
  );
326
326
 
327
327
  EXECUTE format('
328
328
  CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
329
329
  FOR VALUES IN (FALSE);',
330
- emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant || '_active'), emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant)
330
+ emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
331
331
  );
332
332
 
333
333
  EXECUTE format('
334
334
  CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
335
335
  FOR VALUES IN (TRUE);',
336
- emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant || '_archived'), emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant)
336
+ emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
337
337
  );
338
338
 
339
339
  -- For ${s.name} table
@@ -357,7 +357,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(n??`Objects a
357
357
  END LOOP;
358
358
  END;
359
359
  $$ LANGUAGE plpgsql;
360
- `),Le=S(`SELECT emt_add_partition('${R}');`);import{mapRows as St,sql as yt}from"@event-driven-io/dumbo";var De=async(e,t,n)=>{let a=n&&"from"in n?`AND stream_position >= ${n.from}`:"",o=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),i=isNaN(o)?"":`AND stream_position <= ${o}`,p=await St(e.query(yt(`SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
361
- FROM ${r.name}
362
- WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${a} ${i}`,t,n?.partition??R)),m=>{let E=$(m.event_type,m.event_data,m.event_metadata);return{...E,metadata:{...E.metadata,eventId:m.event_id,streamName:t,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return p.length>0?{currentStreamVersion:p[p.length-1].metadata.streamPosition,events:p,streamExists:!0}:{currentStreamVersion:G,events:[],streamExists:!1}};var M=[Se,ye,fe,he,Pe,Ie,Ne,Oe,Re,Ae,ue,Le],k=async e=>{await e.withTransaction(({execute:t})=>t.batchCommand(M))};var ht={projections:[],schema:{autoMigration:"CreateOrUpdate"}},G=0n,Pt=(e,t=ht)=>{let n={connectionString:e,...t.connectionOptions?t.connectionOptions:{}},a="dumbo"in n?n.dumbo:ft(n),o,i=t.schema?.autoMigration===void 0||t.schema?.autoMigration!=="None",p=()=>i?(o||(o=k(a)),o):Promise.resolve(),m=(t.projections??[]).filter(({type:c})=>c==="inline").map(({projection:c})=>c),E=m.length>0?(c,{transaction:d})=>w({projections:m,connection:{connectionString:e,transaction:d},events:c}):void 0;return{schema:{sql:()=>M.join(""),print:()=>console.log(M.join("")),migrate:async()=>{await(o=k(a))}},async aggregateStream(c,d){let{evolve:l,initialState:v,read:I}=d,N=I?.expectedStreamVersion,f=v(),F=await this.readStream(c,d.read),W=F.currentStreamVersion;ne(W,N,G);for(let q of F.events)q&&(f=l(f,q));return{currentStreamVersion:W,state:f,streamExists:F.streamExists}},readStream:async(c,d)=>(await p(),De(a.execute,c,d)),appendToStream:async(c,d,l)=>{await p();let[v,...I]=c.split("-"),N=v&&I.length>0?v:"emt:unknown",f=await ge(a,c,N,d,{...l,preCommitHook:E});if(!f.success)throw new B(-1n,l?.expectedStreamVersion??O);return{nextExpectedStreamVersion:f.nextStreamPosition,createdNewStream:f.nextStreamPosition>=BigInt(d.length)}},close:()=>a.close(),async withSession(c){return await a.withConnection(async d=>{let l={...t,connectionOptions:{connection:d}},v=Pt(e,l);return c({eventStore:v,close:()=>Promise.resolve()})})}}};export{G as PostgreSQLEventStoreDefaultStreamVersion,yn as PostgreSQLProjectionSpec,Le as addDefaultPartition,Ie as addEventsPartitions,Re as addModuleForAllTenantsSQL,Ne as addModuleSQL,Pe as addTablePartitions,Ae as addTenantForAllModulesSQL,Oe as addTenantSQL,ue as appendEventsSQL,ge as appendToStream,dt as assertSQLQueryResultMatches,k as createEventStoreSchema,ht as defaultPostgreSQLOptions,R as defaultTag,ve as documentDoesNotExist,at as documentExists,pe as documentMatchingExists,ot as documentsAreTheSame,rt as documentsMatchingHaveCount,C as emmettPrefix,mt as eventInStream,lt as eventsInStream,r as eventsTable,ye as eventsTableSQL,rn as expectPongoDocuments,hn as expectSQL,Pt as getPostgreSQLEventStore,Dn as globalNames,_ as globalTag,w as handleProjections,fn as newEventsInStream,ct as pongoMultiStreamProjection,st as pongoProjection,dn as pongoSingleStreamProjection,V as postgreSQLProjection,Et as postgreSQLRawBatchSQLProjection,On as postgreSQLRawSQLProjection,De as readStream,he as sanitizeNameSQL,M as schemaSQL,s as streamsTable,Se as streamsTableSQL,fe as subscriptionsTableSQL};
360
+ `),Ne=g(`SELECT emt_add_partition('${O}');`);import{mapRows as ft,sql as yt}from"@event-driven-io/dumbo";var Oe=async(t,e,n)=>{let o=n&&"from"in n?`AND stream_position >= ${n.from}`:"",a=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),r=isNaN(a)?"":`AND stream_position <= ${a}`,l=await ft(t.query(yt(`SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
361
+ FROM ${i.name}
362
+ WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${o} ${r}`,e,n?.partition??O)),m=>{let p=J(m.event_type,m.event_data,m.event_metadata);return{...p,metadata:{...p.metadata,eventId:m.event_id,streamName:e,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return l.length>0?{currentStreamVersion:l[l.length-1].metadata.streamPosition,events:l,streamExists:!0}:{currentStreamVersion:B,events:[],streamExists:!1}};var C=[ue,_e,Te,ge,Se,fe,ye,he,Pe,Ie,pe,Ne],X=async t=>{await t.withTransaction(({execute:e})=>e.batchCommand(C))};var Pt={projections:[],schema:{autoMigration:"CreateOrUpdate"}},B=0n,It=(t,e=Pt)=>{let n={connectionString:t,...e.connectionOptions?e.connectionOptions:{}},o="dumbo"in n?n.dumbo:ht(n),a,r=e.schema?.autoMigration===void 0||e.schema?.autoMigration!=="None",l=()=>r?(a||(a=X(o)),a):Promise.resolve(),m=(e.projections??[]).filter(({type:c})=>c==="inline").map(({projection:c})=>c),p=m.length>0?(c,{transaction:E})=>D({projections:m,connection:{connectionString:t,transaction:E},events:c}):void 0;return{schema:{sql:()=>C.join(""),print:()=>console.log(C.join("")),migrate:async()=>{await(a=X(o))}},async aggregateStream(c,E){let{evolve:d,initialState:v,read:P}=E,I=P?.expectedStreamVersion,f=v(),b=await this.readStream(c,E.read),V=b.currentStreamVersion;K(V,I,B);for(let G of b.events)G&&(f=d(f,G));return{currentStreamVersion:V,state:f,streamExists:b.streamExists}},readStream:async(c,E)=>(await l(),Oe(o.execute,c,E)),appendToStream:async(c,E,d)=>{await l();let[v,...P]=c.split("-"),I=v&&P.length>0?v:"emt:unknown",f=await ve(o,c,I,E,{...d,preCommitHook:p});if(!f.success)throw new $(-1n,d?.expectedStreamVersion??N);return{nextExpectedStreamVersion:f.nextStreamPosition,createdNewStream:f.nextStreamPosition>=BigInt(E.length)}},close:()=>o.close(),async withSession(c){return await o.withConnection(async E=>{let d={...e,connectionOptions:{connection:E}},v=It(t,d);return c({eventStore:v,close:()=>Promise.resolve()})})}}};export{B as PostgreSQLEventStoreDefaultStreamVersion,wn as PostgreSQLProjectionSpec,Ne as addDefaultPartition,fe as addEventsPartitions,Pe as addModuleForAllTenantsSQL,ye as addModuleSQL,Se as addTablePartitions,Ie as addTenantForAllModulesSQL,he as addTenantSQL,pe as appendEventsSQL,ve as appendToStream,Et as assertSQLQueryResultMatches,X as createEventStoreSchema,Pt as defaultPostgreSQLOptions,O as defaultTag,de as documentDoesNotExist,at as documentExists,me as documentMatchingExists,rt as documentsAreTheSame,it as documentsMatchingHaveCount,x as emmettPrefix,dt as eventInStream,lt as eventsInStream,i as eventsTable,_e as eventsTableSQL,gn as expectPongoDocuments,bn as expectSQL,It as getPostgreSQLEventStore,Xn as globalNames,u as globalTag,D as handleProjections,Cn as newEventsInStream,mt as pongoMultiStreamProjection,ct as pongoProjection,Pn as pongoSingleStreamProjection,Q as postgreSQLProjection,pt as postgreSQLRawBatchSQLProjection,$n as postgreSQLRawSQLProjection,Oe as readStream,ge as sanitizeNameSQL,C as schemaSQL,s as streamsTable,ue as streamsTableSQL,Te as subscriptionsTableSQL};
363
363
  //# sourceMappingURL=index.js.map